text:
package com.app.swe443.openbankapp;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Gravity;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;

import static android.content.ContentValues.TAG;

public class MainActivity extends AppCompatActivity
        implements HomeFrag.OnHomeFragMethodSelectedListener, UsersFrag.OnUserFragMethodSelectedListener,  OpenAccountFrag.OnOpenAccountSelected{

    private DrawerLayout Drawer;
    private ActionBarDrawerToggle drawerToggle;
    private ListView drawerList;
    private Toolbar toolbar;
    public ActionBar actionBar;
    private Fragment home_fragment;
    private Fragment newhome_fragment;

    private Fragment users_fragment;

    private Fragment transaction_fragment;
    private Fragment open_account_fragment;
    private Fragment logout_fragment;
    private Fragment contacts_fragment;

    private FragmentManager fm;
    private FragmentTransaction transaction;

    private ArrayList<NavDrawerItem> navDrawerItems;
    private NavDrawerListAdapter adapter;

    private String userID;
    private String username;
    private String name;
    private String email;
    private String phone;
    private String totalBalance="0.0";

    private ArrayList<AccountDisplay> userAccounts;

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

        //INITIALIZE LEFT ACTIONBAR
        //This sets the navigation drawer and the top actionbar.
        Drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawerList = (ListView) findViewById(R.id.left_drawer);
        toolbar = (Toolbar) findViewById(R.id.toolbar);

        setSupportActionBar(toolbar);
        actionBar = getSupportActionBar();
        drawerToggle = new ActionBarDrawerToggle(this, Drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawerToggle.setDrawerIndicatorEnabled(true);
        actionBar.setDisplayHomeAsUpEnabled(true);
        actionBar.setHomeButtonEnabled(true);
        Drawer.addDrawerListener(drawerToggle);
        drawerToggle.syncState();

        fm = getSupportFragmentManager();

        //Information to get when coming from login menu
       userID = getIntent().getStringExtra("userID");
       username = getIntent().getStringExtra("username");
        name = getIntent().getStringExtra("name");
        email = getIntent().getStringExtra("email");
        phone = getIntent().getStringExtra("phone");

        //Initlaize all necessary fragments for MainActivity
        initFragments();
        //Draw the actionbar
        addDrawerItems();
        getUserAccountsFromServer();
        /*
            Add Tina's account set to MainActivity AccountDetails data structure
            ArrayList<Account> needed for account list in homepage
         */
    }

    private void addDrawerItems() {
        navDrawerItems = new ArrayList<NavDrawerItem>();

        String[] navMenuTitles = {"Home", "Update My Information", "Open Account", "Logout" };

        // adding nav drawer items to array
        navDrawerItems.add(new NavDrawerItem(navMenuTitles[0].toString()));
        navDrawerItems.add(new NavDrawerItem(navMenuTitles[1].toString()));
        navDrawerItems.add(new NavDrawerItem(navMenuTitles[2].toString()));
        navDrawerItems.add(new NavDrawerItem(navMenuTitles[3].toString()));

        // setting the nav drawer list adapter
        adapter = new NavDrawerListAdapter(getApplicationContext(), navDrawerItems);

        View headerView = View.inflate(this, R.layout.navigation_drawer_header, null);
        drawerList.addHeaderView(headerView);

        drawerList.setAdapter(adapter);

        drawerList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> a, View v, int position, long id) {
                System.out.println("CLICKED ON "+position);

                switch (position) {
                    case 1:
                        transaction = fm.beginTransaction();
                        transaction.replace(R.id.contentFragment, home_fragment);
                        transaction.addToBackStack(null);
                        transaction.commit();
                        Drawer.closeDrawer(Gravity.LEFT);
                        break;
                    case 2:
                        transaction = fm.beginTransaction();
                        transaction.replace(R.id.contentFragment, users_fragment);
                        transaction.addToBackStack(null);
                        transaction.commit();
                        Drawer.closeDrawer(Gravity.LEFT);
                        break;
                    case 3:
                        transaction = fm.beginTransaction();
                        transaction.replace(R.id.contentFragment, open_account_fragment);
                        transaction.addToBackStack(null);
                        transaction.commit();
                        Drawer.closeDrawer(Gravity.LEFT);
                        break;
                    case 4:
                        Drawer.closeDrawer(Gravity.LEFT);
                        Intent intent = new Intent(v.getContext(), LoginActivity.class);
                        startActivity(intent);
                        finish();
                        break;

                }
            }
        });
    }

    public void backNavigation(View view){
        System.out.println("BACKNAVIGATION FOR HEADER");
        Drawer.closeDrawer(Gravity.START);
    }

    public String[] getUserInfo(){
        String[] userInfo = new String[4];
        userInfo[0] = name;
        userInfo[1] = totalBalance;
        userInfo[2] = email;
        userInfo[3] = phone;
        return userInfo;

    }

    public String[] getAllUserInfo(){
        String[] userInfo = new String[5];
        userInfo[0] = name;
        userInfo[1] = username;
        userInfo[2] = email;
        userInfo[3] = phone;
        userInfo[4] = userID;
        return userInfo;
    }

    /*
        UserFrag changed data, update it here
        userInfo[0] = name.getText().toString();
        userInfo[2] =email.getText().toString();
        userInfo[3] = phone.getText().toString();
        userInfo[1] = username.getText().toString();
     */
    public void updateAllUserInfo(String[] info){
        username = info[1];
        name = info[0];
        email = info[2];
        phone = info[3];
    }

    public void initFragments() {
        /********Home Fragment********/
        home_fragment = new HomeFrag();

        /********Open Account Fragment********/
        open_account_fragment = new OpenAccountFrag();

        /********Transaction Fragments********/
        users_fragment = new UsersFrag();
    }

    /*
        An account was clicked in the homepage, change the screen to display account specific tabs
     */
    public void onAccountSelected(int id) {
        // The user selected the headline of an article from the HeadlinesFragment
        // Do something here to display that article
        getFragmentManager().popBackStack();
        /*
            Send the selected account information to the AccountFrag to display the accounts details
         */
        Intent intent = new Intent(this, AccountDetails.class);
        intent.putExtra("type", userAccounts.get(id).getdType());
        intent.putExtra("accountnum", userAccounts.get(id).getdAccountnum());
        intent.putExtra("balance", userAccounts.get(id).getdBalance());
        intent.putExtra("username", username);
        intent.putExtra("userID", userID);
        intent.putExtra("name", name);
        intent.putExtra("phone", phone);
        intent.putExtra("email", email);

        startActivity(intent);
    }

    public ArrayList<AccountDisplay> getAccounts(){
        return userAccounts;
    }
    public String getUsername(){
        return username;
    }

    public boolean onOptionsItemSelected(MenuItem item){
        System.out.println("ON OPTIONS SELECTED IN MAIN ACTIVITY ");
        return true;
    }

    @Override
    public void onBackPressed() {
        System.out.println("Logout by back press");
        finish();
    }

    public void getUserAccountsFromServer(){
        StringRequest stringRequest;
        RequestQueue queue = Volley.newRequestQueue(getApplicationContext());
        String url = "http://54.87.197.206:8080/SparkServer/api/v1/account?id="+userID;
        stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                System.out.println("OBTAINED USER ACCOUNTS");
//                Toast.makeText(getApplicationContext(),response.toString(),Toast.LENGTH_LONG).show();
                try {
                    JSONArray obj = new JSONArray(response);
                    userAccounts = getAccountsDisplays(obj);
                    goToHomepage();

                }catch(JSONException e){
                    e.printStackTrace();
                    Log.d(TAG,response);
                }

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
            }
        });
        System.out.println("REQUESTING USER ACCOUNTS");
        queue.add(stringRequest);
    }

    public void goToHomepage(){
        //Initiate homepage Fragment when app opens
        transaction = fm.beginTransaction();
        transaction.replace(R.id.contentFragment, home_fragment);//, "Home_FRAGMENT");
        transaction.addToBackStack(null);
        transaction.commit();
    }

    //Read user's accounts from the server responce array
    public ArrayList<AccountDisplay> getAccountsDisplays(JSONArray response){
        ArrayList<AccountDisplay> myDataset = new ArrayList<AccountDisplay>();
        try {
            System.out.println("USER ACCOUNTS REPSONSE IS "+response);
            JSONArray accounts = (JSONArray) response.get(1);
            for(int i=0; i<accounts.length();i++){
                try {
                    JSONObject rec = accounts.getJSONObject(i);
                    System.out.println("Got an account "+rec.toString());
                    String tempbalance = rec.getString("balance");

                    String type = rec.getString("accountType");
                    String accountnum = rec.getString("accountNumber");
                    totalBalance = tempbalance;
                    myDataset.add(new AccountDisplay(type,accountnum,tempbalance));
                }catch(JSONException e){
                    e.printStackTrace();
                    Log.d(TAG,response.toString());
                }
            }
        }catch(JSONException e){
            e.printStackTrace();
            Log.d(TAG,response.toString());
        }
        return myDataset;
    }
//These are for OpenAccountFrag.
    @Override
    public String[] getUsersInfo() {
        return getAllUserInfo();
    }
    @Override
    public void updateUserAccounts() {
       getUserAccountsFromServer();
    }
}

/*
  Helper class to organize attributes that will be dispalyed
*/
class AccountDisplay {
    private String dType;
    private String dAccountnum;
    private String dBalance;

    public AccountDisplay(String type, int num, int balance){
        this.dType = type;
        this.dAccountnum = Integer.toString(num);
        this.dBalance = Integer.toString(balance);
    }

    public AccountDisplay(String type, String num, String balance){
        this.dType = type;
        this.dAccountnum = num;
        this.dBalance = balance;
        //String decimal = balance.substring(0,balance.length()-3)
    }

    public String getdType() {
        return dType;
    }

    public void setdType(String dType) {
        this.dType = dType;
    }

    public String getdAccountnum() {
        return dAccountnum;
    }

    public void setdAccountnum(String dAccountnum) {
        this.dAccountnum = dAccountnum;
    }

    public String getdBalance() {
        return dBalance;
    }

    public void setdBalance(String dBalance) {
        this.dBalance = dBalance;
    }

}


text:
namespace IPC {

AttachmentBrokerWin::AttachmentBrokerWin() {
}

AttachmentBrokerWin::~AttachmentBrokerWin() {
}

void AttachmentBrokerWin::OnReceiveDuplicatedHandle(
    HANDLE,
    BrokerableAttachment::AttachmentId id) {
  // TODO(erikchen): Implement me. http://crbug.com/493414
}

bool AttachmentBrokerWin::SendAttachmentToProcess(
    const BrokerableAttachment* attachment,
    base::ProcessId destination_process) {
  switch (attachment->GetBrokerableType()) {
    case BrokerableAttachment::WIN_HANDLE:
      const internal::HandleAttachmentWin* handle_attachment =
          static_cast<const internal::HandleAttachmentWin*>(attachment);
      internal::HandleAttachmentWin::WireFormat format =
          handle_attachment->GetWireFormat(destination_process);
      return sender_->Send(
          new AttachmentBrokerMsg_DuplicateWinHandle(format));
  }
  return false;
}

bool AttachmentBrokerWin::GetAttachmentWithId(
    BrokerableAttachment::AttachmentId id,
    BrokerableAttachment* attachment) {
  // TODO(erikchen): Implement me. http://crbug.com/493414
  return false;
}

}  // namespace IPC

redpajama_set_name: RedPajamaGithub


text:
//
//  IOfn.h
//  latenttree

#ifndef __latentTree__IOfn__
#define __latentTree__IOfn__
#include "stdafx.h"

using namespace Eigen;
using namespace std;
//////////////////////////////////////////////////////////////////////////////////////////////////////
void read_G_categorical(char* file_name, vector<Node> * mynodelist_ptr, int start);
void read_G_vec(char *file_name, vector<Node> *mynodelist_ptr, int start);
Eigen::SparseMatrix<double> read_G_vec_scalor(char *file_name, vector<Node> *mynodelist_ptr, int start);
Eigen::MatrixXd read_G_dense(char *file_name, char *G_name, int N1, int N2, int start);
/////////////////////////////////////////////////////////////////////////////////////////////////////
void write_vector(char *file_name, vector<int> vector_write);
int write_sparseMat(char *filename, SparseMatrix<double> spmat);
#endif
/*
Eigen::SparseMatrix<double> G_sparse(vector<Edge>& EV, int N);
double** generateRandomGraph(long long int &, int);
double** createAdjacencyMatrix(int N);
void displayAdjacencyMatrix(int** adjMatrix, int N);
void displayAdjacencyMatrix(double** adjMatrix, int N);
vector<Edge> generateRandomEdges(int N, vector<Node*> nodelist, int &count);
*/


text:
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE401_Memory_Leak__char_realloc_22b.c
Label Definition File: CWE401_Memory_Leak.c.label.xml
Template File: sources-sinks-22b.tmpl.c
*/
/*
 * @description
 * CWE: 401 Memory Leak
 * BadSource: realloc Allocate data using realloc()
 * GoodSource: Allocate data on the stack
 * Sinks:
 *    GoodSink: call free() on data
 *    BadSink : no deallocation of data
 * Flow Variant: 22 Control flow: Flow controlled by value of a global variable. Sink functions are in a separate file from sources.
 *
 * */

#include "std_testcase.h"

#include <wchar.h>

#ifndef OMITBAD

/* The global variable below is used to drive control flow in the sink function */
extern int CWE401_Memory_Leak__char_realloc_22_badGlobal;

void CWE401_Memory_Leak__char_realloc_22_badSink(char * data)
{
    if(CWE401_Memory_Leak__char_realloc_22_badGlobal)
    {
        /* POTENTIAL FLAW: No deallocation */
        ; /* empty statement needed for some flow variants */
    }
}

#endif /* OMITBAD */

#ifndef OMITGOOD

/* The global variables below are used to drive control flow in the sink functions. */
extern int CWE401_Memory_Leak__char_realloc_22_goodB2G1Global;
extern int CWE401_Memory_Leak__char_realloc_22_goodB2G2Global;
extern int CWE401_Memory_Leak__char_realloc_22_goodG2BGlobal;

/* goodB2G1() - use badsource and goodsink by setting the static variable to false instead of true */
void CWE401_Memory_Leak__char_realloc_22_goodB2G1Sink(char * data)
{
    if(CWE401_Memory_Leak__char_realloc_22_goodB2G1Global)
    {
        /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */
        printLine("Benign, fixed string");
    }
    else
    {
        /* FIX: Deallocate memory */
        free(data);
    }
}

/* goodB2G2() - use badsource and goodsink by reversing the blocks in the if in the sink function */
void CWE401_Memory_Leak__char_realloc_22_goodB2G2Sink(char * data)
{
    if(CWE401_Memory_Leak__char_realloc_22_goodB2G2Global)
    {
        /* FIX: Deallocate memory */
        free(data);
    }
}

/* goodG2B() - use goodsource and badsink */
void CWE401_Memory_Leak__char_realloc_22_goodG2BSink(char * data)
{
    if(CWE401_Memory_Leak__char_realloc_22_goodG2BGlobal)
    {
        /* POTENTIAL FLAW: No deallocation */
        ; /* empty statement needed for some flow variants */
    }
}

#endif /* OMITGOOD */


text:
package org.lambda4j.operator.ternary;

import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;

class TernaryOperatorTest {

    @Test
    void of_givenExpression_returnsFunctionalInterface() {
        TernaryOperator<String> operator = TernaryOperator.of((t, u, v) -> t);
        Assertions.assertNotNull(operator);
    }

    @Test
    void of_givenNull_returnsNull() {
        TernaryOperator<String> operator = TernaryOperator.of(null);
        Assertions.assertNull(operator);
    }
}


text:
A bash script to install MongoDB on Laravel Homestead with php7
## Usage
Use the following command:

* PHP 7.0

`sudo curl -sS https://raw.githubusercontent.com/zakhttp/Mongostead7/master/mongoHomestead7.sh | sudo sh`

* PHP 7.1

`sudo curl -sS https://raw.githubusercontent.com/zakhttp/Mongostead7/master/mongoHomestead7.1.sh | sudo sh`

Cheers!


text:
class Facade
{
public:
	Facade();
	~Facade();

	/// Call various functions in the sub-system to aggregate its functionality
	bool DoSomething();

private:
	Facade(const Facade &);
	const Facade &operator =(const Facade &);

	class Impl;
	Impl *mImpl;
};

#endif


text:
"""Models representing job queue tables."""
from bidon.db.model import ModelBase

class Job(ModelBase):
  """Model of a job."""
  table_name = "jobs"
  timestamps = ("created_at", None)
  attrs = dict(
    name=None,
    payload=None,
    priority=0,
    serialization_key_id=None,
    started_at=None,
    completed_at=None,
    error_message=None)

class ScheduledJob(ModelBase):
  """Model of a scheduled job."""
  table_name = "scheduled_jobs"
  timestamps = ("created_at", None)
  attrs = dict(
    name=None,
    payload=None,
    priority=0,
    serialization_key_id=None,
    scheduled_at=None)

class SerializationKey(ModelBase):
  """Model of a serialization key. No two jobs with the same serialization key will run at the
  same time.
  """
  table_name = "serialization_keys"
  timestamps = None
  attrs = dict(key=None, active_job_id=None)


text:
<?php

/**
 * Data Helper
 *
 */
class Epoint_SwissPost_Api_Helper_Data extends Mage_Core_Helper_Abstract
{
    /**
     * Setting path for service entry point
     */
    const XML_CONFIG_PATH_API_LOG_STATUS = 'swisspost_api/log/active';
    /**
     * Log file
     *
     */
    const XML_CONFIG_PATH_API_LOG_FILE = 'swisspost_api/log/file';
    /**
     * Allowed list of titles
     *
     */
    const XML_CONFIG_PATH_API_TITLES_LIST = 'swisspost_api/data/titles';

    /**
     * Log exception
     *
     * @param $e
     */
    public static function LogException($e)
    {
        // Log it
        Mage::helper('swisspost_api/MailLog')->sendException($e);
        // Let magento to manage it
        Mage::logException($e);
    }

    /**
     * Log interface
     *
     * @param      $message
     * @param null $logLevel
     */
    public static function log($message, $logLevel = null)
    {
        if ($logLevel == null) {
            $logLevel = Zend_Log::DEBUG;
        }
        if (Mage::getStoreConfig(self::XML_CONFIG_PATH_API_LOG_STATUS)) {
            if (Mage::getStoreConfig(self::XML_CONFIG_PATH_API_LOG_FILE)) {
                Mage::log($message, $logLevel, Mage::getStoreConfig(self::XML_CONFIG_PATH_API_LOG_FILE), true);
            } else {
                Mage::log($message, $logLevel);
            }
        }
    }

    /**
     * Log interface
     *
     * @param ApiResult $result
     */
    public static function logResult(ApiResult $result)
    {

        if (!Mage::getStoreConfig(self::XML_CONFIG_PATH_API_LOG_STATUS)) {
            return;
        }
        $data = array();
        if ($result->isOK()) {
            $logLevel = Zend_Log::DEBUG;
            $data['result'] = $result->getResult();
        } else {
            $logLevel = Zend_Log::ERR;
            $data['error'] = $result->getResult();
        }
        $data['debug'] = $result->getDebug();
        $message = Mage::helper('core')->__('API CALL %s', print_r($data, 1));
        self::log($message, $logLevel);
    }
    /**
     * Return array mapping
     *
     * @param $path
     *
     * @return array|mixed
     */
    public static function getMapping($path)
    {
        $xml = Mage::getConfig()
            ->loadModulesConfiguration('config.xml')
            ->getNode('default/' . $path . '/swisspost_api')
            ->asXML();
        if ($xml) {
            return json_decode(json_encode(simplexml_load_string($xml)), 1);
        }

        return array();
    }

    /**
     * Convert local object, to Swisspost array
     *
     * @param       $fromObject
     * @param array $mapping
     *
     * @return array
     */
    public static function __toSwissPost($fromObject, $mapping = array())
    {
        $data = array();
        if (method_exists($fromObject, 'getData')) {
            $data = $fromObject->getData();
        }
        $swissPostArray = array();
        foreach ($mapping as $swissPostField => $mageField) {
            if ($mageField == '--') {
                $swissPostArray[$swissPostField] = '';
            } else {
                $swissPostArray[$swissPostField] = isset($data[$mageField]) ? $data[$mageField] : null;
            }
        }

        return $swissPostArray;
    }

    /**
     * Convert Swisspost result to array
     *
     * @param            $swissPostItem
     * @param array      $mapping
     * @param bool|false $checkIfSet
     *
     * @return array
     */
    public static function __fromSwissPost($swissPostItem, $mapping = array(), $checkIfSet = false)
    {
        $data = array();
        $swissPostArray = array();
        foreach ($mapping as $mageField => $swissPostField) {
            if ($swissPostField == '--') {
                $data[$mageField] = '';
            } else {
                if ($checkIfSet) {
                    if (isset($swissPostItem[$swissPostField])) {
                        $data[$mageField] = $swissPostItem[$swissPostField];
                    }
                } else {
                    $data[$mageField] = isset($swissPostItem[$swissPostField]) ? $swissPostItem[$swissPostField] : null;
                }
            }
        }

        return $data;
    }

    /**
     * Check if an attribute exists
     *
     * @param $attCode
     *
     * @return bool
     */
    public static function attributeEavExists($attCode)
    {
    	static $processed;
    	if(!isset($processed)){
    		$processed = array();
    	}
    	if(isset($processed[$attCode])){
    		return $processed[$attCode];
    	}
    	$processed[$attCode] = false;
    	$attribute = Mage::getModel('catalog/resource_eav_attribute')->loadByCode('catalog_product', $attCode);
        if ($attribute && $attribute->getId() !== null) {
            $processed[$attCode] = true;
        }
		return $processed[$attCode];
    }

    /**
     * Extract default values from an existing config
     * Ex: company|Microsoft, lines with # will be ignored
     *
     * @param $path
     *
     * @return array
     */
    public static function extractDefaultValues($path)
    {
        return self::textToArray(Mage::getStoreConfig($path));
    }

    /**
     * Convert string to array
     * Ex: company|Microsoft, lines start with # will be ignored
     *
     * @param        $string
     * @param string $attributeSeparator
     * @param string $lineSeparator
     * @param string $ignoreLinesStartWith
     *
     * @return array
     */
    public static function textToArray($string, $attributeSeparator = '|', $lineSeparator = "\n",
        $ignoreLinesStartWith = '#'
    ) {
        $lines = explode($lineSeparator, $string);
        $values = array();
        foreach ($lines as $line) {
            if($attributeSeparator){
              @list($key, $value) = explode($attributeSeparator, trim($line), 2);
              if ($key && $key[0] != $ignoreLinesStartWith) {
                  $values[$key] = $value;
              }
            }elseif(trim($line)){
                $values[$line] = $line;
            }
        }
        return $values;
    }

    /**
     * Check if a title can be configured
     *
     * @param $title
     *
     * @return string
     */
    public function __toTitle($title)
    {
        static $titles;
        if (!isset($titles)) {
            $titles = explode(",", strtolower(Mage::getStoreConfig(self::XML_CONFIG_PATH_API_TITLES_LIST)));
        }
        if (in_array(strtolower($title), $titles)) {
            return $title;
        }

        return '';
    }

    /**
     * Get websites
     *
     * @return array
     */
    public function getWebsites()
    {
        static $websites;
        if (!isset($websites)) {
            $websites = array();
            $_websites = Mage::app()->getWebsites(true);
            foreach ($_websites as $website) {
                $websites[] = $website;
            }
        }

        return $websites;
    }

    /**
     * Get stores with filter
     *
     * @return array
     */
    public function getStores()
    {
        static $stores;
        if (!isset($stores)) {
            $stores = array();
            foreach ($this->getWebsites() as $website) {
                $web_sitestores = $website->getStores();
                foreach ($web_sitestores as $store) {
                    $stores[$store->getCode()] = $store;
                }
            }
        }

        return $stores;
    }

    /**
     * Product loader by sku
     *
     * @param $sku
     *
     * @return false|Mage_Core_Model_Abstract
     */
    public function loadProductBySku($sku)
    {
        $product = Mage::getModel('catalog/product');
        $product->load($product->getIdBySku($sku));

        return $product;
    }

    /**
     * Debugger
     */
    public static function debug()
    {
        $trace = debug_backtrace();
        $lines = array();
        foreach ($trace as $call) {
            $lines[] = "File: " . $call['file'] . ' : line:' . $call['line'] . ': function: ' . $call['function']
                . ' :args:' . implode('|', $call['args']);
        }
        self::log(implode("\n", $lines));
    }
}


text:
__all__ = [
    "BadYamlError",
    "MultipleDocumentsInFpYaml",
    "HttpFetchError",
    "AbortedFetchError",
    ]

class Error(Exception):
  """Base-class for exceptions in this module."""

class BadYamlError(Error):
  """Raise when the mapreduce.yaml file is invalid."""

class MultipleDocumentsInFpYaml(BadYamlError):
  """There's more than one document in fetch_policy.yaml file."""

class HttpFetchError(Error):
  """Raise when the HTTP Status is errored."""

class RedirectError(Error):
  """Raise when the HTTP Status is errored."""

class AbortedFetchError(Error):
  """Raise when need the fetch abort"""


text:
TOP_DIR=$(cd $(dirname "$0") && pwd)
source ${TOP_DIR}/helpers/init_env_variables.sh

CONTROLLER_HOST="node-$(fuel node "$@" | grep controller | awk '{print $1}' | head -1)"
ADMIN_TOKEN="$(ssh ${CONTROLLER_HOST} egrep "^admin_token.*" /etc/keystone/keystone.conf 2>/dev/null | cut -d'=' -f2)"
OS_PUBLIC_AUTH_URL="$(ssh ${CONTROLLER_HOST} ". openrc; keystone catalog --service identity 2>/dev/null | grep publicURL | awk '{print \$4}'")"

keystone_adm() {
    remote_cli keystone --os-token ${ADMIN_TOKEN} --os-endpoint ${OS_PUBLIC_AUTH_URL/5000/35357} $@
}

restore_service_catalog() {
    message "Revert Keystone endpoints"
    local identity_service_id="$(keystone_adm service-list | grep identity | awk '{print $2}')"
    local old_endpoint="$(keystone_adm endpoint-list | grep ${identity_service_id}|awk '{print $2}')"
    local internal_url="$(ssh ${CONTROLLER_HOST} ". openrc; keystone catalog --service identity 2>/dev/null | grep internalURL | awk '{print \$4}'")"
    keystone_adm endpoint-create --region RegionOne --service ${identity_service_id} --publicurl ${OS_PUBLIC_AUTH_URL} --adminurl ${internal_url/5000/35357} --internalurl ${internal_url} 2>/dev/null
    if [ ! -z ${old_endpoint} ]; then
        keystone_adm endpoint-delete ${old_endpoint} 2>/dev/null
    fi
}

cleanup_cloud() {

    restore_service_catalog

    message "Delete the created user, tenant and roles"
    keystone_adm user-role-remove --role SwiftOperator --user demo --tenant demo 2>/dev/null || true
    keystone_adm user-role-remove --role anotherrole --user demo --tenant demo 2>/dev/null || true
    keystone_adm user-role-remove --role admin --user admin --tenant demo 2>/dev/null || true

    keystone_adm role-delete SwiftOperator 2>/dev/null || true
    keystone_adm role-delete anotherrole 2>/dev/null || true
    keystone_adm role-delete heat_stack_user 2>/dev/null || true
    keystone_adm role-delete heat_stack_owner 2>/dev/null || true
    keystone_adm role-delete ResellerAdmin 2>/dev/null || true

    keystone_adm user-delete demo 2>/dev/null || true
    keystone_adm tenant-delete demo 2>/dev/null || true

    message "Delete the created flavors"
    remote_cli nova flavor-delete m1.tempest-nano || true
    remote_cli nova flavor-delete m1.tempest-micro || true

    message "Delete the uploaded CirrOS image"
    remote_cli glance image-delete cirros-${CIRROS_VERSION}-x86_64 || true

    message "Cleanup is done!"
}

cleanup_cloud


text:
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using ExcelDna.Integration;
using ExcelDna.Integration.Rtd;

namespace FinAnSu
{
    public static partial class Web
    {
        private const string RTD_NAME = "RTDServers.ImportServer";
        private const string RTD_SERVER = null;

        [ExcelFunction("Returns a horizontal array of values based on a URL and regular expression.")]
        public static object[,] Import(
            [ExcelArgument("is the full URL of the target website.", Name = "url")] string url,
            [ExcelArgument("is a regular expression pattern where the first backreference (in parentheses)" +
                "is the value you wish to retrieve", Name = "regex_pattern")] object[] patterns,
            [ExcelArgument("is the maximum length of the results array.", Name = "max_length")] int maxLength,
            [ExcelArgument("is whether you want this function to return continuously stream live quotes to the cell.",
                Name = "live_updating")] bool liveUpdating,
            [ExcelArgument("is the number of seconds between update requests (if live_updating is TRUE). " +
                "Defaults to 15 seconds.", Name = "frequency")] double freq,
            [ExcelArgument("is a range or array of headers you wish to display.")] object[] headers)
        {
            if (headers == null || (headers.Length == 1 && (headers[0] is ExcelMissing || headers[0] is ExcelEmpty)))
            {
                headers = new object[] { };
            }
            if (liveUpdating)
            {
                object objFreq = (object)freq;
                if (freq <= 0 || objFreq is ExcelMissing || objFreq is ExcelEmpty) freq = 15;

                // Build list of params to pass to RTD server, and XlCall will only accept strings
                List<string> rtdParams = new List<string>() { url, maxLength.ToString(), freq.ToString(), patterns.Length.ToString() };

                // Somewhat long-winded, but ExcelDna doesn't expose functions containing string[] arguments,
                // so we have to iterate through an object[]-typed list of patterns
                foreach (string pattern in patterns)
                {
                    rtdParams.Add(pattern);
                }
                foreach (string header in headers)
                {
                    rtdParams.Add(header);
                }

                return ParseRtd(XlCall.RTD(RTD_NAME, RTD_SERVER, rtdParams.ToArray()).ToString());
            }
            else
            {
                return GetWebData(url, patterns, maxLength, headers);
            }
        }
    }
}

namespace RTDServers
{
    public class ImportServer : IRtdServer
    {
        private IRTDUpdateEvent _callback;
        private Timer _timer;
        private Dictionary<int, Query> _queries = new Dictionary<int, Query>();

        public int ServerStart(IRTDUpdateEvent CallbackObject)
        {
            // Called when the first RTD topic is requested
            // Sets server to poll for updates every second
            _callback = CallbackObject;
            _timer = new Timer();
            _timer.Tick += Callback;
            _timer.Interval = 1000;
            return 1;
        }
        public void ServerTerminate()
        {
            // Kills timer and queries so they don't run after workbook closes
            _timer.Dispose();
            _queries = null;
        }
        public object ConnectData(int topicId, ref Array Strings, ref bool GetNewValues)
        {
            // Parses 4 parameters to add to query dictionary
            string url = (string)Strings.GetValue(0);
            int maxLength = int.Parse((string)Strings.GetValue(1));
            double freq = double.Parse((string)Strings.GetValue(2));
            int patternsLength = int.Parse((string)Strings.GetValue(3));
            List<string> patterns = new List<string>();
            List<string> headers = new List<string>();
            for (int i = 4; i < Strings.Length; i++)
            {
                if (i > 3 + patternsLength)
                {
                    headers.Add((string)Strings.GetValue(i));
                }
                else
                {
                    patterns.Add((string)Strings.GetValue(i));
                }
            }

            // Adds query, starts timer and returns #WAIT
            _queries.Add(topicId, new Query(url, patterns.ToArray(), maxLength, freq, headers.ToArray()));
            _timer.Start();
            return _queries[topicId].ToString();
        }

        public void DisconnectData(int topicId)
        {
            // Removes query on disconnect
            _queries.Remove(topicId);
        }

        public int Heartbeat()
        {
            // Called by Excel if a given interval has elapsed (returns true)
            return 1;
        }
        public Array RefreshData(ref int topicCount)
        {
            // Called when Excel requests refresh
            // Returns topic count and an array of IDs and values
            object[,] results = new object[2, _queries.Count];
            topicCount = 0;

            // Prevent overwriting by any Query delegates
            lock (_queries)
            {
                foreach (int topicID in _queries.Keys)
                {
                    // Only return results if they've been updated
                    if (_queries[topicID].Updated)
                    {
                        _queries[topicID].Updated = false;
                        results[0, topicCount] = topicID;
                        results[1, topicCount] = _queries[topicID].ToString();
                        topicCount++;
                    }
                }
            }

            _timer.Start();
            return results;
        }

        private void Callback(object sender, EventArgs e)
        {
            // Stops timer and tells all queries to run their async delegates
            _timer.Stop();
            lock (_queries)
            {
                foreach (KeyValuePair<int, Query> q in _queries)
                {
                    q.Value.AsyncImport();
                }
            }
            _callback.UpdateNotify();
        }
    }

    public class Query
    {
        private const string WAIT_TEXT = "#WAIT";
        private delegate void AsyncImporter();
        private AsyncImporter _importer;
        private string _url;
        private string[] _patterns;
        private string[] _headers;
        private int _maxLength;
        private double _freq;
        private DateTime _nextUpdate = DateTime.Now.AddDays(-1);
        private bool _updated;
        private object[,] _results;

        public Query(string url, string[] patterns, int maxLength, double freq, string[] headers)
        {
            _url = url;
            _patterns = patterns;
            _maxLength = maxLength;
            _freq = freq;
            _headers = headers;
            AsyncImport();
        }

        #region Properties
        public string URL
        {
            get { return _url; }
            set { _url = value; }
        }
        public string[] Patterns
        {
            get { return _patterns; }
            set { _patterns = value; }
        }
        public string[] Headers
        {
            get { return _headers; }
            set { _headers = value; }
        }
        public int MaxLength
        {
            get { return _maxLength; }
            set { _maxLength = value; }
        }
        public bool Updated
        {
            get { return _updated; }
            set { _updated = value; }
        }
        public DateTime NextUpdate
        {
            get { return _nextUpdate; }
            set { _nextUpdate = value; }
        }
        #endregion

        public object[,] Results
        {
            get { return _results; }
            set { _results = value; }
        }
        public void AsyncImport()
        {
            // Only runs async based on query frequency
            if (DateTime.Compare(DateTime.Now, _nextUpdate) > 0)
            {
                _nextUpdate = DateTime.Now.AddSeconds(_freq);
                _importer = new AsyncImporter(RunImportDelegate);
                _importer.BeginInvoke(null, null);
            }
        }
        private void RunImportDelegate()
        {
            _results = FinAnSu.Web.GetWebData(_url, _patterns, _maxLength, _headers);
            _updated = true;
        }
        public override string ToString()
        {
            if (_results == null)
            {
                return WAIT_TEXT;
            }
            else
            {
                int height = _results.GetLength(0);
                int width = _results.GetLength(1);
                StringBuilder parsed = new StringBuilder();

                bool firstRow = true;
                for (int row = 0; row < height; row++)
                {
                    bool firstCol = true;

                    // Only append separate row with semicolon if previous row exist (i.e. not first row)
                    if (firstRow)
                    {
                        firstRow = false;
                    }
                    else
                    {
                        parsed.Append(FinAnSu.Web.ROW_SEPARATOR);
                    }
                    for (int col = 0; col < width; col++)
                    {
                        // Only append separate row with comma if previous row exist (i.e. not first row)
                        if (firstCol)
                        {
                            firstCol = false;
                        }
                        else
                        {
                            parsed.Append(FinAnSu.Web.COLUMN_SEPARATOR);
                        }
                        parsed.Append(_results[row, col].ToString());
                    }
                }
                return parsed.ToString();
            }
        }
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Http.Controllers;
using System.Web.Http.Description;

namespace DigitalLabels.WebApi.Infrastructure
{
    public class ApiDocumentationProvider : IDocumentationProvider
    {
        public string GetDocumentation(HttpParameterDescriptor parameterDescriptor)
        {
            string doc = "";

            var attr = parameterDescriptor
                .ActionDescriptor
                .GetCustomAttributes<ApiParameterDocAttribute>()
                .FirstOrDefault(p => p.Parameter == parameterDescriptor.ParameterName);

            if (attr != null)
            {
                doc = attr.Documentation;
            }

            return doc;
        }

        public string GetDocumentation(HttpActionDescriptor actionDescriptor)
        {
            string doc = "";

            var attr = actionDescriptor
                .GetCustomAttributes<ApiDocAttribute>()
                .FirstOrDefault();

            if (attr != null)
            {
                doc = attr.Documentation;
            }

            return doc;
        }
    }
}


text:
<title>Readline Bare Essentials - Debugging with GDB</title>
<meta http-equiv="Content-Type" content="text/html">
<meta name="description" content="Debugging with GDB">
<meta name="generator" content="makeinfo 4.13">
<link title="Top" rel="start" href="index.html#Top">
<link rel="up" href="Readline-Interaction.html#Readline-Interaction" title="Readline Interaction">
<link rel="next" href="Readline-Movement-Commands.html#Readline-Movement-Commands" title="Readline Movement Commands">
<link href="http://www.gnu.org/software/texinfo/" rel="generator-home" title="Texinfo Homepage">

<meta http-equiv="Content-Style-Type" content="text/css">

Next: Readline Movement Commands,
Up: Readline Interaction

32.2.1 Readline Bare Essentials

In order to enter characters into the line, simply type them.  The typed
character appears where the cursor was, and then the cursor moves one
space to the right.  If you mistype a character, you can use your
erase character to back up and delete the mistyped character.

Sometimes you may mistype a character, and
not notice the error until you have typed several other characters.  In
that case, you can type C-b to move the cursor to the left, and then
correct your mistake.  Afterwards, you can move the cursor to the right
with C-f.

When you add text in the middle of a line, you will notice that characters
to the right of the cursor are `pushed over' to make room for the text
that you have inserted.  Likewise, when you delete text behind the cursor,
characters to the right of the cursor are `pulled back' to fill in the
blank space created by the removal of the text.  A list of the bare
essentials for editing the text of an input line follows.

C-b
Move back one character.

C-f
Move forward one character.

<DEL> or <Backspace>
Delete the character to the left of the cursor.

C-d
Delete the character underneath the cursor.

Printing characters
Insert the character into the line at the cursor.

C-_ or C-x C-u
Undo the last editing command.  You can undo all the way back to an
empty line.

(Depending on your configuration, the <Backspace> key be set to
delete the character to the left of the cursor and the <DEL> key set
to delete the character underneath the cursor, like C-d, rather
than the character to the left of the cursor.)


text:
import React from 'react';
import styled from '@emotion/styled';
import PropTypes from 'prop-types';

import AnnotatedText from 'app/components/events/meta/annotatedText';
import {getMeta} from 'app/components/events/meta/metaProxy';
import TextOverflow from 'app/components/textOverflow';
import {t} from 'app/locale';
import space from 'app/styles/space';
import {Meta} from 'app/types';

import ContextSummaryNoSummary from './contextSummaryNoSummary';
import generateClassName from './generateClassName';
import Item from './item';

type Props = {
  data: Data;
};

type Data = {
  name: string;
  vendor_name?: string;
};

type VersionElement = {
  subject: string;
  value: string;
  meta?: Meta;
};

const ContextSummaryGPU = ({data}: Props) => {
  if (Object.keys(data).length === 0 || !data.name) {
    return <ContextSummaryNoSummary title={t('Unknown GPU')} />;
  }

  const renderName = () => {
    const meta = getMeta(data, 'name');

    return <AnnotatedText value={data.name} meta={meta} />;
  };

  let className = generateClassName(data.name);

  const getVersionElement = (): VersionElement => {
    if (data.vendor_name) {
      className = generateClassName(data.vendor_name);
      return {
        subject: t('Vendor:'),
        value: data.vendor_name,
        meta: getMeta(data, 'vendor_name'),
      };
    }

    return {
      subject: t('Vendor:'),
      value: t('Unknown'),
    };
  };

  const versionElement = getVersionElement();

  return (
    <Item className={className} icon={}>

{renderName()}

      <TextOverflow isParagraph>
        <Subject>{versionElement.subject}</Subject>
        <AnnotatedText value={versionElement.value} meta={versionElement.meta} />
      </TextOverflow>
    </Item>
  );
};

ContextSummaryGPU.propTypes = {
  data: PropTypes.object.isRequired,
};

export default ContextSummaryGPU;

const Subject = styled('strong')`
  margin-right: ${space(0.5)};
`;


text:
package org.locationtech.geomesa.utils.geotools.converters

import java.util.Date

import org.geotools.factory.Hints
import org.geotools.util.{Converter, ConverterFactory}
import org.locationtech.geomesa.utils.text.DateParsing

class JavaTimeConverterFactory extends ConverterFactory {
  def createConverter(source: Class[_], target: Class[_], hints: Hints): Converter = {
    if (classOf[Date].isAssignableFrom(source) && classOf[String].isAssignableFrom(target)) {
      JavaTimeConverterFactory.DateToStringConverter
    } else if (classOf[Date].isAssignableFrom(target) && classOf[String].isAssignableFrom(source)) {
      JavaTimeConverterFactory.StringToDateConverter
    } else {
      null
    }
  }
}

object JavaTimeConverterFactory {

  private val DateToStringConverter = new Converter {
    override def convert[T](source: AnyRef, target: Class[T]): T =
      DateParsing.formatDate(source.asInstanceOf[Date]).asInstanceOf[T]
  }

  private val StringToDateConverter = new Converter {
    override def convert[T](source: AnyRef, target: Class[T]): T =
      DateParsing.parseDate(source.asInstanceOf[String]).asInstanceOf[T]
  }
}


text:
[![GitHub license](https://img.shields.io/badge/license-MIT-blue.svg)](https://raw.githubusercontent.com/anisibor/NoConnection/master/LICENSE.md)
[![release](https://img.shields.io/badge/release-v1.0-blue.svg)](https://github.com/anisibor/NoConnection/releases)

# NoConnection

Application that shows the status of the Internet connection in status bar on your mac.

![q](https://pp.userapi.com/c639427/v639427163/2583b/mZvz-KuJE7M.jpg)

## Getting Started

You can just [download](https://github.com/anisibor/NoConnection/releases/) .app file, or compile it by yourself.

### Prerequisites

You need [CocoaPods](https://cocoapods.org/) for getting dependencies.

Locate to project root foler and run

```
pod install
```

After that you can compile the project in Xcode.

## License

This project is licensed under the MIT License - see the [LICENSE.md](LICENSE.md) file for details


text:
package net.dvt32.models;

public class MovieSummary {

    private String id;
    private String title;
    private String overview;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getOverview() {
        return overview;
    }

    public void setOverview(String overview) {
        this.overview = overview;
    }

}


text:
import re
import json
import flask
import hashlib
import jsonschema
from .version_data import VERSION, COMMIT

from indexd import auth

from indexd.errors import AuthError, AuthzError
from indexd.errors import UserError

from .schema import PUT_RECORD_SCHEMA
from .schema import POST_RECORD_SCHEMA
from .schema import RECORD_ALIAS_SCHEMA
from .schema import BUNDLE_SCHEMA
from .schema import UPDATE_ALL_VERSIONS_SCHEMA

from .errors import NoRecordFound
from .errors import MultipleRecordsFound
from .errors import RevisionMismatch
from .errors import UnhealthyCheck

from cdislogging import get_logger
from indexd.drs.blueprint import bundle_to_drs

logger = get_logger("indexd/index blueprint", log_level="info")

blueprint = flask.Blueprint("index", __name__)

blueprint.config = dict()
blueprint.index_driver = None
blueprint.dist = []

ACCEPTABLE_HASHES = {
    "md5": re.compile(r"^[0-9a-f]{32}$").match,
    "sha1": re.compile(r"^[0-9a-f]{40}$").match,
    "sha256": re.compile(r"^[0-9a-f]{64}$").match,
    "sha512": re.compile(r"^[0-9a-f]{128}$").match,
    "crc": re.compile(r"^[0-9a-f]{8}$").match,
    "etag": re.compile(r"^[0-9a-f]{32}(-\d+)?$").match,
}

def validate_hashes(**hashes):
    """
    Validate hashes against known and valid hashing algorithms.
    """
    if not all(h in ACCEPTABLE_HASHES for h in hashes):
        raise UserError("invalid hash types specified")

    if not all(ACCEPTABLE_HASHES[h](v) for h, v in hashes.items()):
        raise UserError("invalid hash values specified")

@blueprint.route("/index/", methods=["GET"])
def get_index(form=None):
    """
    Returns a list of records.
    """
    limit = flask.request.args.get("limit")
    start = flask.request.args.get("start")
    page = flask.request.args.get("page")

    ids = flask.request.args.get("ids")
    if ids:
        ids = ids.split(",")
        if start is not None or limit is not None or page is not None:
            raise UserError("pagination is not supported when ids is provided")
    try:
        limit = 100 if limit is None else int(limit)
    except ValueError as err:
        raise UserError("limit must be an integer")

    if limit < 0 or limit > 1024:
        raise UserError("limit must be between 0 and 1024")

    if page is not None:
        try:
            page = int(page)
        except ValueError as err:
            raise UserError("page must be an integer")

    size = flask.request.args.get("size")
    try:
        size = size if size is None else int(size)
    except ValueError as err:
        raise UserError("size must be an integer")

    if size is not None and size < 0:
        raise UserError("size must be > 0")

    uploader = flask.request.args.get("uploader")

    # TODO: Based on indexclient, url here should be urls instead. Or change urls to url in indexclient.
    urls = flask.request.args.getlist("url")

    file_name = flask.request.args.get("file_name")

    version = flask.request.args.get("version")

    hashes = flask.request.args.getlist("hash")
    hashes = {h: v for h, v in (x.split(":", 1) for x in hashes)}

    validate_hashes(**hashes)
    hashes = hashes if hashes else None

    metadata = flask.request.args.getlist("metadata")
    metadata = {k: v for k, v in (x.split(":", 1) for x in metadata)}

    acl = flask.request.args.get("acl")
    if acl is not None:
        acl = [] if acl == "null" else acl.split(",")

    authz = flask.request.args.get("authz")
    if authz is not None:
        authz = [] if authz == "null" else authz.split(",")

    urls_metadata = flask.request.args.get("urls_metadata")
    if urls_metadata:
        try:
            urls_metadata = json.loads(urls_metadata)
        except ValueError:
            raise UserError("urls_metadata must be a valid json string")

    negate_params = flask.request.args.get("negate_params")
    if negate_params:
        try:
            negate_params = json.loads(negate_params)
        except ValueError:
            raise UserError("negate_params must be a valid json string")

    form = flask.request.args.get("form") if not form else form
    if form == "bundle":
        records = blueprint.index_driver.get_bundle_list(
            start=start, limit=limit, page=page
        )
    elif form == "all":
        records = blueprint.index_driver.get_bundle_and_object_list(
            limit=limit,
            page=page,
            start=start,
            size=size,
            urls=urls,
            acl=acl,
            authz=authz,
            hashes=hashes,
            file_name=file_name,
            version=version,
            uploader=uploader,
            metadata=metadata,
            ids=ids,
            urls_metadata=urls_metadata,
            negate_params=negate_params,
        )
    else:
        records = blueprint.index_driver.ids(
            start=start,
            limit=limit,
            page=page,
            size=size,
            file_name=file_name,
            version=version,
            urls=urls,
            acl=acl,
            authz=authz,
            hashes=hashes,
            uploader=uploader,
            ids=ids,
            metadata=metadata,
            urls_metadata=urls_metadata,
            negate_params=negate_params,
        )

    base = {
        "ids": ids,
        "records": records,
        "limit": limit,
        "start": start,
        "page": page,
        "size": size,
        "file_name": file_name,
        "version": version,
        "urls": urls,
        "acl": acl,
        "authz": authz,
        "hashes": hashes,
        "metadata": metadata,
    }

    return flask.jsonify(base), 200

@blueprint.route("/urls/", methods=["GET"])
def get_urls():
    """
    Returns a list of urls.
    """
    ids = flask.request.args.get("ids")
    if ids:
        ids = ids.split(",")
    hashes = flask.request.args.getlist("hash")
    hashes = {h: v for h, v in (x.split(":", 1) for x in hashes)}
    size = flask.request.args.get("size")
    if size:
        try:
            size = int(size)
        except TypeError:
            raise UserError("size must be an integer")

        if size < 0:
            raise UserError("size must be >= 0")

    try:
        start = int(flask.request.args.get("start", 0))
    except TypeError:
        raise UserError("start must be an integer")

    try:
        limit = int(flask.request.args.get("limit", 100))
    except TypeError:
        raise UserError("limit must be an integer")

    if start < 0:
        raise UserError("start must be >= 0")

    if limit < 0:
        raise UserError("limit must be >= 0")

    if limit > 1024:
        raise UserError("limit must be <= 1024")

    validate_hashes(**hashes)

    urls = blueprint.index_driver.get_urls(
        size=size, ids=ids, hashes=hashes, start=start, limit=limit
    )

    ret = {"urls": urls, "limit": limit, "start": start, "size": size, "hashes": hashes}

    return flask.jsonify(ret), 200

@blueprint.route("/index/<path:record>", methods=["GET"])
def get_index_record(record):
    """
    Returns a record.
    """

    ret = blueprint.index_driver.get_with_nonstrict_prefix(record)

    return flask.jsonify(ret), 200

@blueprint.route("/index/", methods=["POST"])
def post_index_record():
    """
    Create a new record.
    """
    try:
        jsonschema.validate(flask.request.json, POST_RECORD_SCHEMA)
    except jsonschema.ValidationError as err:
        raise UserError(err)

    authz = flask.request.json.get("authz", [])
    auth.authorize("create", authz)

    did = flask.request.json.get("did")
    form = flask.request.json["form"]
    size = flask.request.json["size"]
    urls = flask.request.json["urls"]
    acl = flask.request.json.get("acl", [])

    hashes = flask.request.json["hashes"]
    file_name = flask.request.json.get("file_name")
    metadata = flask.request.json.get("metadata")
    urls_metadata = flask.request.json.get("urls_metadata")
    version = flask.request.json.get("version")
    baseid = flask.request.json.get("baseid")
    uploader = flask.request.json.get("uploader")

    did, rev, baseid = blueprint.index_driver.add(
        form,
        did,
        size=size,
        file_name=file_name,
        metadata=metadata,
        urls_metadata=urls_metadata,
        version=version,
        urls=urls,
        acl=acl,
        authz=authz,
        hashes=hashes,
        baseid=baseid,
        uploader=uploader,
    )

    ret = {"did": did, "rev": rev, "baseid": baseid}

    return flask.jsonify(ret), 200

@blueprint.route("/index/blank/", methods=["POST"])
def post_index_blank_record():
    """
    Create a blank new record with only uploader and optionally
    file_name fields filled
    """
    body = flask.request.get_json() or {}
    uploader = body.get("uploader")
    file_name = body.get("file_name")
    authz = body.get("authz")

    # authorize done in add_blank_record
    did, rev, baseid = blueprint.index_driver.add_blank_record(
        uploader=uploader, file_name=file_name, authz=authz
    )

    ret = {"did": did, "rev": rev, "baseid": baseid}

    return flask.jsonify(ret), 201

@blueprint.route("/index/blank/<path:record>", methods=["POST"])
def add_index_blank_record_version(record):
    """
    Create a new blank version of the record with this GUID.
    Authn/authz fields carry over from the previous version of the record.
    Only uploader and optionally file_name fields are filled.
    Returns the GUID of the new blank version and the baseid common to all versions
    of the record.
    """
    body = flask.request.get_json() or {}
    new_did = body.get("did")
    uploader = body.get("uploader")
    file_name = body.get("file_name")
    authz = body.get("authz")

    # authorize done in add_blank_version for the existing record's authz
    did, baseid, rev = blueprint.index_driver.add_blank_version(
        record, new_did=new_did, uploader=uploader, file_name=file_name, authz=authz
    )

    ret = {"did": did, "baseid": baseid, "rev": rev}

    return flask.jsonify(ret), 201

@blueprint.route("/index/blank/<path:record>", methods=["PUT"])
def put_index_blank_record(record):
    """
    Update a blank record with size, hashes and url
    """
    rev = flask.request.args.get("rev")

    body = flask.request.get_json() or {}
    size = body.get("size")
    hashes = body.get("hashes")
    urls = body.get("urls")
    authz = body.get("authz")

    # authorize done in update_blank_record
    did, rev, baseid = blueprint.index_driver.update_blank_record(
        did=record, rev=rev, size=size, hashes=hashes, urls=urls, authz=authz
    )
    ret = {"did": did, "rev": rev, "baseid": baseid}

    return flask.jsonify(ret), 200

@blueprint.route("/index/<path:record>", methods=["PUT"])
def put_index_record(record):
    """
    Update an existing record.
    """
    try:
        jsonschema.validate(flask.request.json, PUT_RECORD_SCHEMA)
    except jsonschema.ValidationError as err:
        raise UserError(err)

    rev = flask.request.args.get("rev")

    # authorize done in update
    did, baseid, rev = blueprint.index_driver.update(record, rev, flask.request.json)

    ret = {"did": did, "baseid": baseid, "rev": rev}

    return flask.jsonify(ret), 200

@blueprint.route("/index/<path:record>", methods=["DELETE"])
def delete_index_record(record):
    """
    Delete an existing record.
    """
    rev = flask.request.args.get("rev")
    if rev is None:
        raise UserError("no revision specified")

    # authorize done in delete
    blueprint.index_driver.delete(record, rev)

    return "", 200

@blueprint.route("/index/<path:record>", methods=["POST"])
def add_index_record_version(record):
    """
    Add a record version
    """
    try:
        jsonschema.validate(flask.request.json, POST_RECORD_SCHEMA)
    except jsonschema.ValidationError as err:
        raise UserError(err)

    new_did = flask.request.json.get("did")
    form = flask.request.json["form"]
    size = flask.request.json["size"]
    urls = flask.request.json["urls"]
    acl = flask.request.json.get("acl", [])
    authz = flask.request.json.get("authz", [])
    hashes = flask.request.json["hashes"]
    file_name = flask.request.json.get("file_name")
    metadata = flask.request.json.get("metadata")
    urls_metadata = flask.request.json.get("urls_metadata")
    version = flask.request.json.get("version")

    # authorize done in add_version for both the old and new authz
    did, baseid, rev = blueprint.index_driver.add_version(
        record,
        form,
        new_did=new_did,
        size=size,
        urls=urls,
        acl=acl,
        authz=authz,
        file_name=file_name,
        metadata=metadata,
        urls_metadata=urls_metadata,
        version=version,
        hashes=hashes,
    )

    ret = {"did": did, "baseid": baseid, "rev": rev}

    return flask.jsonify(ret), 200

@blueprint.route("/index/<path:record>/aliases", methods=["GET"])
def get_aliases(record):
    """
    Get all aliases associated with this DID / GUID
    """
    # error handling done in driver
    aliases = blueprint.index_driver.get_aliases_for_did(record)

    aliases_payload = {"aliases": [{"value": alias} for alias in aliases]}
    return flask.jsonify(aliases_payload), 200

@blueprint.route("/index/<path:record>/aliases", methods=["POST"])
def append_aliases(record):
    """
    Append one or more aliases to aliases already associated with this
    DID / GUID, if any.
    """
    # we set force=True so that if MIME type of request is not application/JSON,
    # get_json will still throw a UserError.
    aliases_json = flask.request.get_json(force=True)
    try:
        jsonschema.validate(aliases_json, RECORD_ALIAS_SCHEMA)
    except jsonschema.ValidationError as err:
        logger.warning(f"Bad request body:\n{err}")
        raise UserError(err)

    aliases = [record["value"] for record in aliases_json["aliases"]]

    # authorization and error handling done in driver
    blueprint.index_driver.append_aliases_for_did(aliases, record)

    aliases = blueprint.index_driver.get_aliases_for_did(record)
    aliases_payload = {"aliases": [{"value": alias} for alias in aliases]}
    return flask.jsonify(aliases_payload), 200

@blueprint.route("/index/<path:record>/aliases", methods=["PUT"])
def replace_aliases(record):
    """
    Replace all aliases associated with this DID / GUID
    """
    # we set force=True so that if MIME type of request is not application/JSON,
    # get_json will still throw a UserError.
    aliases_json = flask.request.get_json(force=True)
    try:
        jsonschema.validate(aliases_json, RECORD_ALIAS_SCHEMA)
    except jsonschema.ValidationError as err:
        logger.warning(f"Bad request body:\n{err}")
        raise UserError(err)

    aliases = [record["value"] for record in aliases_json["aliases"]]

    # authorization and error handling done in driver
    blueprint.index_driver.replace_aliases_for_did(aliases, record)

    aliases_payload = {"aliases": [{"value": alias} for alias in aliases]}
    return flask.jsonify(aliases_payload), 200

@blueprint.route("/index/<path:record>/aliases", methods=["DELETE"])
def delete_all_aliases(record):
    # authorization and error handling done in driver
    blueprint.index_driver.delete_all_aliases_for_did(record)

    return flask.jsonify("Aliases deleted successfully"), 200

@blueprint.route("/index/<path:record>/aliases/<path:alias>", methods=["DELETE"])
def delete_one_alias(record, alias):
    # authorization and error handling done in driver
    blueprint.index_driver.delete_one_alias_for_did(alias, record)

    return flask.jsonify("Aliases deleted successfully"), 200

@blueprint.route("/index/<path:record>/versions", methods=["GET"])
def get_all_index_record_versions(record):
    """
    Get all record versions
    """
    ret = blueprint.index_driver.get_all_versions(record)

    return flask.jsonify(ret), 200

@blueprint.route("/index/<path:record>/versions", methods=["PUT"])
def update_all_index_record_versions(record):
    """
    Update metadata for all record versions.
    NOTE currently the only fields that can be updated for all versions are
    (`authz`, `acl`).
    """
    request_json = flask.request.get_json(force=True)
    try:
        jsonschema.validate(request_json, UPDATE_ALL_VERSIONS_SCHEMA)
    except jsonschema.ValidationError as err:
        logger.warning(f"Bad request body:\n{err}")
        raise UserError(err)

    acl = request_json.get("acl")
    authz = request_json.get("authz")
    # authorization and error handling done in driver
    ret = blueprint.index_driver.update_all_versions(record, acl=acl, authz=authz)

    return flask.jsonify(ret), 200

@blueprint.route("/index/<path:record>/latest", methods=["GET"])
def get_latest_index_record_versions(record):
    """
    Get the latest record version
    """
    has_version = flask.request.args.get("has_version", "").lower() == "true"
    ret = blueprint.index_driver.get_latest_version(record, has_version=has_version)

    return flask.jsonify(ret), 200

@blueprint.route("/_dist", methods=["GET"])
def get_dist_config():
    """
    Returns the dist configuration
    """

    return flask.jsonify(blueprint.dist), 200

@blueprint.route("/_status", methods=["GET"])
def health_check():
    """
    Health Check.
    """
    blueprint.index_driver.health_check()

    return "Healthy", 200

@blueprint.route("/_stats", methods=["GET"])
def stats():
    """
    Return indexed data stats.
    """

    filecount = blueprint.index_driver.len()
    totalfilesize = blueprint.index_driver.totalbytes()

    base = {"fileCount": filecount, "totalFileSize": totalfilesize}

    return flask.jsonify(base), 200

@blueprint.route("/_version", methods=["GET"])
def version():
    """
    Return the version of this service.
    """

    base = {"version": VERSION, "commit": COMMIT}

    return flask.jsonify(base), 200

def get_checksum(data):
    """
    Collect checksums from bundles and objects in the bundle for compute_checksum
    """
    if "hashes" in data:
        return data["hashes"][list(data["hashes"])[0]]
    elif "checksums" in data:
        return data["checksums"][0]["checksum"]
    elif "checksum" in data:
        return data["checksum"]

def compute_checksum(checksums):
    """
    Checksum created by sorting alphabetically then concatenating first layer of bundles/objects.

    Args:
        checksums (list): list of checksums from the first layer of bundles and objects

    Returns:
        md5 checksum
    """
    checksums.sort()
    checksum = "".join(checksums)
    return {
        "checksum": hashlib.md5(checksum.encode("utf-8")).hexdigest(),
        "type": "md5",
    }

@blueprint.route("/bundle/", methods=["POST"])
def post_bundle():
    """
    Create a new bundle
    """
    auth.authorize("create", ["/services/indexd/bundles"])
    try:
        jsonschema.validate(flask.request.json, BUNDLE_SCHEMA)
    except jsonschema.ValidationError as err:
        raise UserError(err)

    name = flask.request.json.get("name")
    bundles = flask.request.json.get("bundles")
    bundle_id = flask.request.json.get("bundle_id")
    size = flask.request.json.get("size") if flask.request.json.get("size") else 0
    description = (
        flask.request.json.get("description")
        if flask.request.json.get("description")
        else ""
    )
    version = (
        flask.request.json.get("version") if flask.request.json.get("version") else ""
    )
    aliases = (
        flask.request.json.get("aliases") if flask.request.json.get("aliases") else []
    )

    if len(bundles) == 0:
        raise UserError("Bundle data required.")

    if len(bundles) != len(set(bundles)):
        raise UserError("Duplicate GUID in bundles.")

    if bundle_id in bundles:
        raise UserError("Bundle refers to itself.")

    bundle_data = []
    checksums = []

    # TODO: Remove this after updating to jsonschema>=3.0.0
    if flask.request.json.get("checksums"):
        hashes = {
            checksum["type"]: checksum["checksum"]
            for checksum in flask.request.json.get("checksums")
        }
        validate_hashes(**hashes)

    # get bundles/records that already exists and add it to bundle_data
    for bundle in bundles:
        data = get_index_record(bundle)[0]
        data = data.json
        size += data["size"] if not flask.request.json.get("size") else 0
        checksums.append(get_checksum(data))
        data = bundle_to_drs(data, expand=True, is_content=True)
        bundle_data.append(data)
    checksum = (
        flask.request.json.get("checksums")
        if flask.request.json.get("checksums")
        else [compute_checksum(checksums)]
    )

    ret = blueprint.index_driver.add_bundle(
        bundle_id=bundle_id,
        name=name,
        size=size,
        bundle_data=json.dumps(bundle_data),
        checksum=json.dumps(checksum),
        description=description,
        version=version,
        aliases=json.dumps(aliases),
    )

    return flask.jsonify({"bundle_id": ret[0], "name": ret[1], "contents": ret[2]}), 200

@blueprint.route("/bundle/", methods=["GET"])
def get_bundle_record_list():
    """
    Returns a list of bundle records.
    """

    form = (
        flask.request.args.get("form") if flask.request.args.get("form") else "bundle"
    )

    return get_index(form=form)

@blueprint.route("/bundle/<path:bundle_id>", methods=["GET"])
def get_bundle_record_with_id(bundle_id):
    """
    Returns a record given bundle_id
    """

    expand = True if flask.request.args.get("expand") == "true" else False

    ret = blueprint.index_driver.get_with_nonstrict_prefix(bundle_id)

    ret = bundle_to_drs(ret, expand=expand, is_content=False)

    return flask.jsonify(ret), 200

@blueprint.route("/bundle/<path:bundle_id>", methods=["DELETE"])
def delete_bundle_record(bundle_id):
    """
    Delete bundle record given bundle_id
    """
    auth.authorize("delete", ["/services/indexd/bundles"])
    blueprint.index_driver.delete_bundle(bundle_id)

    return "", 200

@blueprint.errorhandler(NoRecordFound)
def handle_no_record_error(err):
    return flask.jsonify(error=str(err)), 404

@blueprint.errorhandler(MultipleRecordsFound)
def handle_multiple_records_error(err):
    return flask.jsonify(error=str(err)), 409

@blueprint.errorhandler(UserError)
def handle_user_error(err):
    return flask.jsonify(error=str(err)), 400

@blueprint.errorhandler(AuthError)
def handle_auth_error(err):
    return flask.jsonify(error=str(err)), 403

@blueprint.errorhandler(AuthzError)
def handle_authz_error(err):
    return flask.jsonify(error=str(err)), 401

@blueprint.errorhandler(RevisionMismatch)
def handle_revision_mismatch(err):
    return flask.jsonify(error=str(err)), 409

@blueprint.errorhandler(UnhealthyCheck)
def handle_unhealthy_check(err):
    return "Unhealthy", 500

@blueprint.record
def get_config(setup_state):
    config = setup_state.app.config["INDEX"]
    blueprint.index_driver = config["driver"]
    if "DIST" in setup_state.app.config:
        blueprint.dist = setup_state.app.config["DIST"]


text:
<?php

declare(strict_types=1);

namespace Respect\Validation\Rules;

use stdClass;

use function array_filter;
use function is_array;
use function is_numeric;
use function is_string;
use function trim;

/**
 * Validates if the given input is not a blank value (null, zeros, empty strings or empty arrays, recursively).
 *
 * @author Danilo Correa <danilosilva87@gmail.com>
 * @author Henrique Moody <henriquemoody@gmail.com>
 */
final class NotBlank extends AbstractRule
{
    /**
     * {@inheritDoc}
     */
    public function validate($input): bool
    {
        if (is_numeric($input)) {
            return $input != 0;
        }

        if (is_string($input)) {
            $input = trim($input);
        }

        if ($input instanceof stdClass) {
            $input = (array) $input;
        }

        if (is_array($input)) {
            $input = array_filter($input, __METHOD__);
        }

        return !empty($input);
    }
}


text:
B3D.MirrorRTT = function ( width, height, options ) {

	B3D.Mirror.call( this, width, height, options );

	this.geometry.setDrawRange( 0, 0 ); // avoid rendering geometry

};

B3D.MirrorRTT.prototype = Object.create( B3D.Mirror.prototype );


text:
import mock
from oslo_utils import uuidutils

from sahara.service.edp.data_sources.base import DataSourceType

import testtools

class DataSourceBaseTestCase(testtools.TestCase):
    def setUp(self):
        super(DataSourceBaseTestCase, self).setUp()
        self.ds_base = DataSourceType()

    def test_construct_url_no_placeholders(self):
        base_url = "swift://container/input"
        job_exec_id = uuidutils.generate_uuid()

        url = self.ds_base.construct_url(base_url, job_exec_id)

        self.assertEqual(base_url, url)

    def test_construct_url_job_exec_id_placeholder(self):
        base_url = "swift://container/input.%JOB_EXEC_ID%.out"
        job_exec_id = uuidutils.generate_uuid()

        url = self.ds_base.construct_url(base_url, job_exec_id)

        self.assertEqual(
            "swift://container/input." + job_exec_id + ".out", url)

    def test_construct_url_randstr_placeholder(self):
        base_url = "swift://container/input.%RANDSTR(4)%.%RANDSTR(7)%.out"
        job_exec_id = uuidutils.generate_uuid()

        url = self.ds_base.construct_url(base_url, job_exec_id)

        self.assertRegex(
            url, "swift://container/input\.[a-z]{4}\.[a-z]{7}\.out")

    def test_construct_url_randstr_and_job_exec_id_placeholder(self):
        base_url = "swift://container/input.%JOB_EXEC_ID%.%RANDSTR(7)%.out"
        job_exec_id = uuidutils.generate_uuid()

        url = self.ds_base.construct_url(base_url, job_exec_id)

        self.assertRegex(
            url, "swift://container/input." + job_exec_id + "\.[a-z]{7}\.out")

    def test_get_urls(self):
        url = 'test://url'
        cluster = mock.Mock()
        job_exec_id = 'test_id'

        self.assertEqual((url, url), self.ds_base.get_urls(url,
                         cluster, job_exec_id))


text:
'use strict';

const models = require('./index');

/**
 * Data Lake Store virtual network rule information.
 *
 * @extends models['SubResource']
 */
class VirtualNetworkRule extends models['SubResource'] {
  /**
   * Create a VirtualNetworkRule.
   * @property {string} [subnetId] The resource identifier for the subnet.
   */
  constructor() {
    super();
  }

  /**
   * Defines the metadata of VirtualNetworkRule
   *
   * @returns {object} metadata of VirtualNetworkRule
   *
   */
  mapper() {
    return {
      required: false,
      serializedName: 'VirtualNetworkRule',
      type: {
        name: 'Composite',
        className: 'VirtualNetworkRule',
        modelProperties: {
          id: {
            required: false,
            readOnly: true,
            serializedName: 'id',
            type: {
              name: 'String'
            }
          },
          name: {
            required: false,
            readOnly: true,
            serializedName: 'name',
            type: {
              name: 'String'
            }
          },
          type: {
            required: false,
            readOnly: true,
            serializedName: 'type',
            type: {
              name: 'String'
            }
          },
          subnetId: {
            required: false,
            readOnly: true,
            serializedName: 'properties.subnetId',
            type: {
              name: 'String'
            }
          }
        }
      }
    };
  }
}

module.exports = VirtualNetworkRule;


text:
#include "ruby/ruby.h"
#include "ruby/debug.h"

static size_t
di_size(const void *dummy)
{
    return sizeof(void *);
}

static const rb_data_type_t di_data_type = {
    "simple_// debugger",
    {0, 0, di_size,},
};

static const rb_debug_inspector_t *
di_get_dc(VALUE self)
{
    const rb_debug_inspector_t *dc;
    TypedData_Get_Struct(self, const rb_debug_inspector_t, &di_data_type, dc);
    if (dc == 0) {
	rb_raise(rb_eArgError, "invalid debug context");
    }
    return dc;
}

static VALUE
di_backtrace_locations(VALUE self)
{
    const rb_debug_inspector_t *dc = di_get_dc(self);
    return rb_debug_inspector_backtrace_locations(dc);
}

static VALUE
di_binding(VALUE self, VALUE index)
{
    const rb_debug_inspector_t *dc = di_get_dc(self);
    return rb_debug_inspector_frame_binding_get(dc, NUM2INT(index));
}

static VALUE
di_frame_class(VALUE self, VALUE index)
{
    const rb_debug_inspector_t *dc = di_get_dc(self);
    return rb_debug_inspector_frame_class_get(dc, NUM2INT(index));
}

static VALUE
di_frame_iseq(VALUE self, VALUE index)
{
    const rb_debug_inspector_t *dc = di_get_dc(self);
    return rb_debug_inspector_frame_iseq_get(dc, NUM2INT(index));
}

static VALUE
di_frame_self(VALUE self, VALUE index)
{
    const rb_debug_inspector_t *dc = di_get_dc(self);
    return rb_debug_inspector_frame_self_get(dc, NUM2INT(index));
}

static VALUE
breakpoint_i(const rb_debug_inspector_t *dc, void *ptr)
{
    VALUE self = (VALUE)ptr;
    VALUE result;

    /* should protect */
    DATA_PTR(self) = (void *)dc;
    result = rb_yield(self);
    return result;
}

static VALUE
di_open_body(VALUE self)
{
    return rb_debug_inspector_open(breakpoint_i, (void *)self);
}

static VALUE
di_open_ensure(VALUE self)
{
    DATA_PTR(self) = 0;
    return self;
}

static VALUE
di_open_s(VALUE klass)
{
    VALUE self = TypedData_Wrap_Struct(klass, &di_data_type, 0);
    return rb_ensure(di_open_body, self, di_open_ensure, self);
}

void
Init_debug_inspector(void)
{
    VALUE rb_cRubyVM = rb_const_get(rb_cObject, rb_intern("RubyVM"));
    VALUE cDebugInspector = rb_define_class_under(rb_cRubyVM, "DebugInspector", rb_cObject);

    rb_undef_alloc_func(cDebugInspector);
    rb_define_singleton_method(cDebugInspector, "open", di_open_s, 0);
    rb_define_method(cDebugInspector, "backtrace_locations", di_backtrace_locations, 0);
    rb_define_method(cDebugInspector, "frame_binding", di_binding, 1);
    rb_define_method(cDebugInspector, "frame_class", di_frame_class, 1);
    rb_define_method(cDebugInspector, "frame_iseq", di_frame_iseq, 1);
    rb_define_method(cDebugInspector, "frame_self", di_frame_self, 1);
}


text:
/* Public Domain Curses */

#include <curspriv.h>

RCSID("$Id: color.c,v 1.83 2008/07/13 16:08:18 wmcbrine Exp $")

/*man-start**************************************************************

  Name:                                                         color

  Synopsis:
        int start_color(void);
        int init_pair(short pair, short fg, short bg);
        int init_color(short color, short red, short green, short blue);
        bool has_colors(void);
        bool can_change_color(void);
        int color_content(short color, short *red, short *green, short *blue);
        int pair_content(short pair, short *fg, short *bg);

        int assume_default_colors(int f, int b);
        int use_default_colors(void);

        int PDC_set_line_color(short color);

  Description:
        To use these routines, start_color() must be called, usually
        immediately after initscr(). Colors are always used in pairs,
        referred to as color-pairs. A color-pair consists of a
        foreground color and a background color. A color-pair is
        initialized via init_pair(). After initialization, COLOR_PAIR(n)
        can be used like any other video attribute.

        start_color() initializes eight basic colors (black, red, green,
        yellow, blue, magenta, cyan, and white), and two global
        variables; COLORS and COLOR_PAIRS (respectively defining the
        maximum number of colors and color-pairs the terminal is capable
        of displaying).

        init_pair() changes the definition of a color-pair. It takes
        three arguments: the number of the color-pair to be redefined,
        and the new values of the foreground and background colors. The
        pair number must be between 0 and COLOR_PAIRS - 1, inclusive.
        The foreground and background must be between 0 and COLORS - 1,
        inclusive. If the color pair was previously initialized, the
        screen is refreshed, and all occurrences of that color-pair are
        changed to the new definition.

        has_colors() indicates if the terminal supports, and can
        maniplulate color. It returns TRUE or FALSE.

        can_change_color() indicates if the terminal has the capability
        to change the definition of its colors.

        pair_content() is used to determine what the colors of a given
        color-pair consist of.

        assume_default_colors() and use_default_colors() emulate the
        ncurses extensions of the same names. assume_default_colors(f,
        b) is essentially the same as init_pair(0, f, b) (which isn't
        allowed); it redefines the default colors. use_default_colors()
        allows the use of -1 as a foreground or background color with
        init_pair(), and calls assume_default_colors(-1, -1); -1
        represents the foreground or background color that the terminal
        had at startup. If the environment variable PDC_ORIGINAL_COLORS
        is set at the time start_color() is called, that's equivalent to
        calling use_default_colors().

        PDC_set_line_color() is used to set the color, globally, for
        the color of the lines drawn for the attributes: A_UNDERLINE,
        A_OVERLINE, A_LEFTLINE and A_RIGHTLINE. A value of -1 (the
        default) indicates that the current foreground color should be
        used.

        NOTE: COLOR_PAIR() and PAIR_NUMBER() are implemented as macros.

  Return Value:
        All functions return OK on success and ERR on error, except for
        has_colors() and can_change_colors(), which return TRUE or FALSE.

  Portability                                X/Open    BSD    SYS V
        start_color                             Y       -      3.2
        init_pair                               Y       -      3.2
        init_color                              Y       -      3.2
        has_colors                              Y       -      3.2
        can_change_color                        Y       -      3.2
        color_content                           Y       -      3.2
        pair_content                            Y       -      3.2
        assume_default_colors                   -       -       -
        use_default_colors                      -       -       -
        PDC_set_line_color                      -       -       -

**man-end****************************************************************/

#include <stdlib.h>
#include <string.h>

int COLORS = 0;
int COLOR_PAIRS = PDC_COLOR_PAIRS;

bool pdc_color_started = FALSE;

/* pair_set[] tracks whether a pair has been set via init_pair() */

static bool pair_set[PDC_COLOR_PAIRS];
static bool default_colors = FALSE;
static short first_col = 0;

int start_color(void)
{
    PDC_LOG(("start_color() - called\n"));

    if (SP->mono)
        return ERR;

    pdc_color_started = TRUE;

    PDC_set_blink(FALSE);   /* Also sets COLORS, to 8 or 16 */

    if (!default_colors && SP->orig_attr && getenv("PDC_ORIGINAL_COLORS"))
        default_colors = TRUE;

    PDC_init_atrtab();

    memset(pair_set, 0, PDC_COLOR_PAIRS);

    return OK;
}

static void _normalize(short *fg, short *bg)
{
    if (*fg == -1)
        *fg = SP->orig_attr ? SP->orig_fore : COLOR_WHITE;

    if (*bg == -1)
        *bg = SP->orig_attr ? SP->orig_back : COLOR_BLACK;
}

int init_pair(short pair, short fg, short bg)
{
    PDC_LOG(("init_pair() - called: pair %d fg %d bg %d\n", pair, fg, bg));

    if (!pdc_color_started || pair < 1 || pair >= COLOR_PAIRS ||
        fg < first_col || fg >= COLORS || bg < first_col || bg >= COLORS)
        return ERR;

    _normalize(&fg, &bg);

    /* To allow the PDC_PRESERVE_SCREEN option to work, we only reset
       curscr if this call to init_pair() alters a color pair created by
       the user. */

    if (pair_set[pair])
    {
        short oldfg, oldbg;

        PDC_pair_content(pair, &oldfg, &oldbg);

        if (oldfg != fg || oldbg != bg)
            curscr->_clear = TRUE;
    }

    PDC_init_pair(pair, fg, bg);

    pair_set[pair] = TRUE;

    return OK;
}

bool has_colors(void)
{
    PDC_LOG(("has_colors() - called\n"));

    return !(SP->mono);
}

int init_color(short color, short red, short green, short blue)
{
    PDC_LOG(("init_color() - called\n"));

    if (color < 0 || color >= COLORS || !PDC_can_change_color() ||
        red < 0 || red > 1000 || green < 0 || green > 1000 ||
        blue < 0 || blue > 1000)
        return ERR;

    return PDC_init_color(color, red, green, blue);
}

int color_content(short color, short *red, short *green, short *blue)
{
    PDC_LOG(("color_content() - called\n"));

    if (color < 0 || color >= COLORS || !red || !green || !blue)
        return ERR;

    if (PDC_can_change_color())
        return PDC_color_content(color, red, green, blue);
    else
    {
        /* Simulated values for platforms that don't support palette
           changing */

        short maxval = (color & 8) ? 1000 : 680;

        *red = (color & COLOR_RED) ? maxval : 0;
        *green = (color & COLOR_GREEN) ? maxval : 0;
        *blue = (color & COLOR_BLUE) ? maxval : 0;

        return OK;
    }
}

bool can_change_color(void)
{
    PDC_LOG(("can_change_color() - called\n"));

    return PDC_can_change_color();
}

int pair_content(short pair, short *fg, short *bg)
{
    PDC_LOG(("pair_content() - called\n"));

    if (pair < 0 || pair >= COLOR_PAIRS || !fg || !bg)
        return ERR;

    return PDC_pair_content(pair, fg, bg);
}

int assume_default_colors(int f, int b)
{
    PDC_LOG(("assume_default_colors() - called: f %d b %d\n", f, b));

    if (f < -1 || f >= COLORS || b < -1 || b >= COLORS)
        return ERR;

    if (pdc_color_started)
    {
        short fg, bg, oldfg, oldbg;

        fg = f;
        bg = b;

        _normalize(&fg, &bg);

        PDC_pair_content(0, &oldfg, &oldbg);

        if (oldfg != fg || oldbg != bg)
            curscr->_clear = TRUE;

        PDC_init_pair(0, fg, bg);
    }

    return OK;
}

int use_default_colors(void)
{
    PDC_LOG(("use_default_colors() - called\n"));

    default_colors = TRUE;
    first_col = -1;

    return assume_default_colors(-1, -1);
}

int PDC_set_line_color(short color)
{
    PDC_LOG(("PDC_set_line_color() - called: %d\n", color));

    if (color < -1 || color >= COLORS)
        return ERR;

    SP->line_color = color;

    return OK;
}

void PDC_init_atrtab(void)
{
    int i;
    short fg, bg;

    if (pdc_color_started && !default_colors)
    {
        fg = COLOR_WHITE;
        bg = COLOR_BLACK;
    }
    else
        fg = bg = -1;

    _normalize(&fg, &bg);

    for (i = 0; i < PDC_COLOR_PAIRS; i++)
        PDC_init_pair(i, fg, bg);
}


text:
"use strict";

var Schema = require('mongoose').Schema;
var SessionSchema = require('./session-schema');

var EventSchema = new Schema({
    title: { type: String, required: true },
    uniqueTitle: { type: String, required: true, index: { unique: true } },
    cover: { type: String }, //Buffer
    description: { type: String },
    difficulty: { type: String },
    eventDate: { type: String, required: true },
    location: {
        x: { type: Number },
        y: { type: Number }
    },

    sessions: [ SessionSchema ], //{ type: mongoose.Schema.Types.ObjectId, ref: 'Session', required: true, index: true }

    googlePlusAlbum: { type: String },

    active: { type: Boolean, default: false },

    //agenda: { }, //probablemente sea un atributo virtual
    //tags: [ String ], //seteado automaticamente segun sesiones
    //liveStream: { type: String },
    //gdg: { type: String, default: "GDGMendoza" },
    //releaseDate: { type: Date },

    createdAt: { type: Date, default: Date.now },
    modifiedAt: { type: Date, default: Date.now }
});

module.exports = EventSchema;


text:
package com.mobenga.ngen.xml.parser.example;

import com.mobenga.ngen.xml.parser.AttributeMapping;
import com.mobenga.ngen.xml.parser.ElementParserSettings;
import com.mobenga.ngen.xml.parser.ElementTextMapping;
import com.mobenga.ngen.xml.parser.Mappings;
import com.mobenga.ngen.xml.parser.example.model.Event;
import com.mobenga.ngen.xml.parser.example.model.Market;
import com.mobenga.ngen.xml.util.MappingUtil;

public class EventMapperExample1 implements Mappings {

    @Override
    public ElementParserSettings getSettings() {
        return event();
    }

    private ElementParserSettings event() {

        ElementParserSettings settings = new ElementParserSettings("event");

        settings.setElementStartProcessor(objectBranch -> {
            Event event = new Event();
            objectBranch.put(Event.class, event);
        });

        settings.setAttributeMappings(
                new AttributeMapping<>(Event.class, Event::setId, MappingUtil::getFirst, "id"),
                new AttributeMapping<>(Event.class, Event::setName, MappingUtil::getFirst, "name")
        );

        settings.setSubElementParsers(market());

        settings.setElementTextMappings(new ElementTextMapping<>(Event.class, Event::setMainMarket, MappingUtil::getElementText));

        return settings;
    }

    private ElementParserSettings market() {
        ElementParserSettings settings = new ElementParserSettings("market");

        settings.setElementStartProcessor(objectBranch -> objectBranch.put(Market.class, new Market()));

        settings.setAttributeMappings(
                new AttributeMapping<>(Market.class, Market::setId, MappingUtil::getFirst, "id"),
                new AttributeMapping<>(Market.class, Market::setName, MappingUtil::getFirst, "name")
        );

        settings.setElementEndProcessor(objectBranch -> {
            Event event = objectBranch.getInstance(Event.class);
            Market market = objectBranch.pop(Market.class);
            event.getMarkets().add(market);
        });
        return settings;
    }
}


text:
import React from "react";
import Markdown from "./Markdown";
import { Entry } from "./TocFrame";
import Meta from "./Meta";

/**
 *  Common block at the top of most pages.
 *
 *  Title, highlights, cover image, etc.
 *
 */
export default function render(props: Entry & { children?: React.ReactNode }) {
  //   const Wrapper = props.hero? ({children}:any) =>
{children}
 :

  return (
    <>
      <Meta {...props} />

{props.title}

          {props.tags && props.tags.some((tag: string) => tag == "Beta") && (
            Beta
          )}

        {props.coverImage && (

        )}

        {props.highlights && (

            <Markdown source={props.highlights} />

        )}

        {props.tags && props.tags.some((tag: string) => tag == "Beta") && (

              This feature is currently in Beta. Please contact our{" "}
              support team to learn
              more about how to enroll.

        )}
        {props.contents && <Markdown source={props.contents} />}
        {props.children && props.children}

    </>
  );
}


text:
using System;
using System.Collections.Generic;
using Caliburn.Micro;
using Caliburn.Micro.Contrib.Decorators;
using NUnit.Framework;

namespace CMContrib.Test.Decorators.Rescue
{
    [TestFixture]
    public class InnerResultIsCancelled
    {
        IResult _inner;

        [SetUp]
        public void SetUp()
        {
            _inner = TestHelper.MockResult(true, null).Object;
        }

        [Test]
        public void ResultIsStillCancelled()
        {
            var sut = new RescueResultDecorator(_inner, ex => TestHelper.EmptyCoroutine, true);

            var args = sut.BlockingExecute();

            Assert.IsTrue(args.WasCancelled);
            Assert.IsNull(args.Error);
        }

        [Test]
        public void RescueIsNotExecuted()
        {
            bool rescueInvoked = false;

            Func<Exception, IEnumerable<IResult>> rescue = ex =>
                                                               {
                                                                   rescueInvoked = true;
                                                                   return TestHelper.EmptyCoroutine;
                                                               };

            var sut = new RescueResultDecorator(_inner, rescue, true);

            sut.BlockingExecute();

            Assert.IsFalse(rescueInvoked);
        }
    }
}


text:
package org.zstack.header.network.service;

import org.zstack.header.message.APIEvent;

import java.sql.Timestamp;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

public class APIAttachNetworkServiceProviderToL2NetworkEvent extends APIEvent {
    private NetworkServiceProviderInventory inventory;

    public APIAttachNetworkServiceProviderToL2NetworkEvent() {
        super(null);
    }

    public APIAttachNetworkServiceProviderToL2NetworkEvent(String apiId) {
        super(apiId);
    }

    public NetworkServiceProviderInventory getInventory() {
        return inventory;
    }

    public void setInventory(NetworkServiceProviderInventory inventory) {
        this.inventory = inventory;
    }

    public static APIAttachNetworkServiceProviderToL2NetworkEvent __example__() {
        APIAttachNetworkServiceProviderToL2NetworkEvent event = new APIAttachNetworkServiceProviderToL2NetworkEvent();

        NetworkServiceProviderVO vo = new NetworkServiceProviderVO();
        NetworkServiceProviderL2NetworkRefVO refVO = new NetworkServiceProviderL2NetworkRefVO();

        refVO.setId(1L);
        refVO.setL2NetworkUuid(uuid());
        refVO.setNetworkServiceProviderUuid(uuid());

        Set<NetworkServiceProviderL2NetworkRefVO> setRefVO = new HashSet<>();

        Set<String> nst = new HashSet<>();
        nst.add("SecurityGroup");

        vo.setUuid(uuid());
        vo.setAttachedL2NetworkRefs(setRefVO);
        vo.setName("SecurityGroup");
        vo.setType("SecurityGroup");
        vo.setCreateDate(new Timestamp(org.zstack.header.message.DocUtils.date));
        vo.setLastOpDate(new Timestamp(org.zstack.header.message.DocUtils.date));
        vo.setNetworkServiceTypes(nst);

        NetworkServiceProviderInventory nsp = NetworkServiceProviderInventory.valueOf(vo);

        event.setInventory(nsp);
        return event;
    }

}


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

  <title>{% if page.title %}{{ page.title }}{% else %}{{ site.title }}{% endif %}</title>
  <meta name="description" content="{% if page.excerpt %}{{ page.excerpt | strip_html | strip_newlines | truncate: 160 }}{% else %}{{ site.description }}{% endif %}">

  <link rel="canonical" href="{{ page.url | replace:'index.html','' | prepend: site.baseurl | prepend: site.url }}">

  <link rel="stylesheet" href="{{ "/assets/css/bootstrap.min.css" | prepend: site.baseurl }}">
  <!-- <link rel="stylesheet" href="{{ "/assets/css/icard_resume.css" | prepend: site.baseurl }}"> -->
  <link rel="stylesheet" href="{{ "/assets/css/font-awesome.min.css" | prepend: site.baseurl }}">
  <link rel="stylesheet" href="{{ "/assets/css/blog.css" | prepend: site.baseurl }}" >
  <link rel="stylesheet" href="{{ "/assets/css/syntax.css" | prepend: site.baseurl }}">

  <link rel="icon" type="image/png" href="{{ site.favicon }}">

  <!-- Google fonts -->
  <link rel='stylesheet' href='//fonts.googleapis.com/css?family=Open+Sans:300' type='text/css'>
  <link rel='stylesheet' href='//fonts.googleapis.com/css?family=Source+Sans+Pro' type='text/css'>

  <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
  <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
  <!--[if lt IE 9]>
  <script src="assets/js/html5shiv.min.js"></script>
  <script src="assets/js/respond.min.js"></script>
  <![endif]-->

</head>

{% include googleanalytics.html %}