text:
@implementation FMPApiController

+ (instancetype)sharedInstance {

    static FMPApiController *__sharedInstance;
    static dispatch_once_t onceToken;

    dispatch_once(&onceToken, ^{

        NSURL *baseURL = [NSURL URLWithString:API_BASE_URL];

        __sharedInstance = [[FMPApiController alloc] initWithBaseURL:baseURL];
        __sharedInstance.responseSerializer = [AFJSONResponseSerializer serializer];
        __sharedInstance.requestSerializer = [AFJSONRequestSerializer serializer];

    });
    return __sharedInstance;
}

+ (void)registerUserWithEmailAddress:(NSString *)emailAddress password:(NSString *)password completionHandler:(void (^)(BOOL, NSError *))handler {

    NSMutableDictionary *parameters = [@{
                                         @"email" : emailAddress,
                                         @"password"  : password
                                         } mutableCopy];

    [SVProgressHUD show];

    [[FMPApiController sharedInstance] POST:@"users/register" parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {

        [SVProgressHUD showSuccessWithStatus:@"Registration successful!"];

        NSLog(@"Registration successfull.\nResponse object:\n%@", responseObject);
        handler(YES, nil);

    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {

        [self handleError:error operationError:operation.responseObject];
        handler(NO, error);

    }];

}

+ (void)loginWithEmailAddress:(NSString *)emailAddress password:(NSString *)password completionHandler:(void (^)(BOOL, NSError *))handler {

    NSMutableDictionary *parameters = [@{
                                         @"email" : emailAddress,
                                         @"password"  : password
                                         } mutableCopy];

    [SVProgressHUD show];
    [[FMPApiController sharedInstance] POST:@"users/login" parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {

        [SVProgressHUD dismiss];
        NSString *token = [operation.response allHeaderFields][@"Authorization"];
        if (token) {
            [FMPDefaultsController saveToken:token];
            [FMPApiController sharedInstance].accessToken = token;
            [[FMPApiController sharedInstance].requestSerializer setValue:token forHTTPHeaderField:@"Authorization"];

            NSLog(@"Login successfull");
            handler(YES, nil);
        } else {
            handler(NO, nil);
        }

    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {

        [self handleError:error operationError:operation.responseObject];
        handler(NO, error);
    }];
}

+ (void)addDeviceWithName:(NSString *)name description:(NSString *)description vendorID:(NSString*)vendorID completionHandler:(void (^)(BOOL, NSError *))handler {

    NSMutableDictionary *parameters = [@{
                                         @"name" : name,
                                         @"description"  : description,
                                         @"device_id" : vendorID
                                         } mutableCopy];

    [SVProgressHUD show];
    [[FMPApiController sharedInstance] POST:@"device" parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {

        [SVProgressHUD showSuccessWithStatus:@"Device added successfully!"];
        handler(YES,nil);

    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {

        [self handleError:error operationError:operation.responseObject];
        handler(NO, error);
    }];
}

+ (void)updateDeviceWithID:(NSNumber*)dID name:(NSString *)name description:(NSString *)description vendorID:(NSString*)vendorID completionHandler:(void (^)(BOOL, NSError *))handler {

    NSMutableDictionary *parameters = [@{
                                         @"name" : name,
                                         @"description"  : description,
                                         @"device_id" : vendorID
                                         } mutableCopy];

    [SVProgressHUD show];
    [[FMPApiController sharedInstance] PUT:[NSString stringWithFormat:@"devices/%@",dID] parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {

        [SVProgressHUD dismiss];
        handler(YES,nil);

    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {

        [self handleError:error operationError:operation.responseObject];
        handler(NO, error);
    }];
}

+ (void)updateATSettingsForDeviceWithID:(NSInteger)dID email:(NSString*)email emailPeriod:(NSInteger)emailPeriod period:(NSInteger)period completionHandler:(void (^)(BOOL, NSError *))handler {

    NSMutableDictionary *parameters = [@{
                                         @"email" : email,
                                         @"email_period"  : @(emailPeriod),
                                         @"period" : @(period)
                                         } mutableCopy];

    [SVProgressHUD show];
    [[FMPApiController sharedInstance] PUT:[NSString stringWithFormat:@"devices/%d/settings", dID] parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {

        [SVProgressHUD showSuccessWithStatus:@"Settings saved successfully!"];
        handler(YES,nil);

    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {

        [self handleError:error operationError:operation.responseObject];
        handler(NO, error);
    }];

}

+ (void)getDevicesWithCompletionHandler:(void (^)(BOOL, NSArray*, NSError *))handler {

    [[FMPApiController sharedInstance] GET:@"devices" parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {

        NSArray *devices = @[];
        if ([responseObject isKindOfClass:[NSDictionary class]]) {
            if ([((NSDictionary*)responseObject) objectForKey:@"devices"]) {
                devices = [((NSDictionary*)responseObject) objectForKey:@"devices"];
            }
        }

        handler(YES, devices, nil);

    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {

        [self handleError:error operationError:operation.responseObject];
        handler(NO, nil, error);
    }];

}

+ (void)getLocationsForDeviceWithID:(NSNumber*)deviceID completionHandler:(void (^)(BOOL, NSArray*, NSError *))handler {

    NSString *path = [NSString stringWithFormat:@"devices/%@/locations", deviceID];

    [[FMPApiController sharedInstance] GET:path parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {

        NSArray *locations = @[];
        if ([responseObject isKindOfClass:[NSDictionary class]]) {
            if ([((NSDictionary*)responseObject) objectForKey:@"locations"]) {
                locations = [((NSDictionary*)responseObject) objectForKey:@"locations"];
            }
        }
        handler(YES, locations, nil);

    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {

        [self handleError:error operationError:operation.responseObject];
        handler(NO, nil, error);
    }];

}

+ (void)getSettingsForDeviceWithId:(NSInteger)deviceID withCompletionHandler:(void (^)(BOOL, NSDictionary*, NSError *))handler {

    NSString *path = [NSString stringWithFormat:@"devices/%d/settings", deviceID];
    [SVProgressHUD showWithStatus:@"Getting current settings"];
    [[FMPApiController sharedInstance] GET:path parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        [SVProgressHUD dismiss];
        NSDictionary *settings = @{};
        if ([responseObject isKindOfClass:[NSDictionary class]]) {
            if ([((NSDictionary*)responseObject) objectForKey:@"settings"]) {
                settings = [((NSDictionary*)responseObject) objectForKey:@"settings"];
            }
        }

        handler(YES, settings, nil);

    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {

        [self handleError:error operationError:operation.responseObject];
        handler(NO, nil, error);
    }];

}

+ (void)deregisterDeviceWithID:(NSNumber*)dID completionHandler:(void (^)(BOOL, NSError *))handler {

    NSString *path;
    if (dID) {
        path = [NSString stringWithFormat:@"devices/%d", dID.integerValue];
    } else {
        [SVProgressHUD showErrorWithStatus:@"Device unregistered. Sign in again."];
        [self logout];
        return;
    }
    [[FMPApiController sharedInstance] DELETE:path parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {

        [SVProgressHUD showSuccessWithStatus:@"Device deregistered!"];
        handler(YES, nil);

    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {

        [self handleError:error operationError:operation.responseObject];
        handler(NO, error);

    }];

}

+ (void)logout {

    [FMPApiController sharedInstance].accessToken = nil;

    [FMPDefaultsController clearDefaults];
    [AppDelegate showLoginViewController];
}

+ (void)handleError:(NSError*)error operationError:(NSString*)operationError {

    if (operationError) {
        if ([operationError isKindOfClass:[NSDictionary class]]) {
            NSDictionary *dic = ((NSDictionary*)operationError)[@"errors"];
            if ([[dic allKeys] firstObject]) {
                NSString *errorMessage = dic[[dic allKeys][0]];
                [SVProgressHUD showErrorWithStatus:errorMessage];
                return;
            }
        }
    }

    if (error.code == 403) {
        [self logout];
        [SVProgressHUD showErrorWithStatus:@"Session expired. Please sign in again."];
    } else {
        [SVProgressHUD showErrorWithStatus:error.localizedDescription];
    }

}

@end


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

package com.google.devtools.build.lib.runtime.commands.info;

import com.google.common.base.Supplier;
import com.google.devtools.build.lib.analysis.config.BuildConfigurationValue;
import com.google.devtools.build.lib.runtime.CommandEnvironment;
import com.google.devtools.build.lib.runtime.InfoItem;
import com.google.devtools.build.lib.util.StringUtilities;

/** Info item for the used heap size after garbage collection. */
public final class UsedHeapSizeAfterGcInfoItem extends InfoItem {
  public UsedHeapSizeAfterGcInfoItem() {
    super(
        "used-heap-size-after-gc",
        "The amount of used memory in bytes after a call to System.gc().",
        true);
  }

  @Override
  public byte[] get(
      Supplier<BuildConfigurationValue> configurationSupplier, CommandEnvironment env) {
    System.gc();
    return print(StringUtilities.prettyPrintBytes(InfoItemUtils.getMemoryUsage().getUsed()));
  }
}

redpajama_set_name: RedPajamaGithub


text:
Public Class frmStart

    'Private Sub frmStart_Load(sender As Object, e As EventArgs) Handles MyBase.Load

    'End Sub

    Private Sub btnNew_Click(sender As Object, e As EventArgs) Handles btnNew.Click
        If lblFilePath.Text = "File Path" Then
            MessageBox.Show("Please Select a Database file path before proceeding")
        Else
            frmEdit.intContactUUID = 0
            My.Forms.frmEdit.Show()
            Me.Hide()
        End If
    End Sub

    Private Sub btnSearch_Click(sender As Object, e As EventArgs) Handles btnSearch.Click
        If lblFilePath.Text = "File Path" Then
            MessageBox.Show("Please Select a Database file path before proceeding")
        Else

            My.Forms.frmSearch.Show()
            Me.Hide()
            frmEdit.intContactUUID = 0

        End If

    End Sub

    Public Sub btnDataBase_Click(sender As Object, e As EventArgs) Handles btnDataBase.Click

        'Allows user to select the file path for their database
        If ofdDatabase.ShowDialog = System.Windows.Forms.DialogResult.OK Then
            'lblfilepath.text is changed to the file path of the selected database
            lblFilePath.Text = ofdDatabase.FileName
        End If

    End Sub

    'Is needed to terminate the application.  There was an issue in which the program would hang in the background when the frmStart was closed
    Private Sub frmStart_FormClosed(sender As Object, e As System.Windows.Forms.FormClosedEventArgs) Handles Me.FormClosed
        End
    End Sub

    Private Sub btnClose_Click(sender As Object, e As EventArgs) Handles btnClose.Click
        Me.Close()
    End Sub
End Class


text:
/**
 * \file
 *
 * This file contains storage for the trust anchors for the validator.
 */

#ifndef VALIDATOR_VAL_ANCHOR_H
#define VALIDATOR_VAL_ANCHOR_H
#include "util/rbtree.h"
#include "util/locks.h"
struct trust_anchor;
struct config_file;
struct ub_packed_rrset_key;
struct autr_point_data;
struct autr_global_data;
struct sldns_buffer;

/**
 * Trust anchor store.
 * The tree must be locked, while no other locks (from trustanchors) are held.
 * And then an anchor searched for.  Which can be locked or deleted.  Then
 * the tree can be unlocked again.  This means you have to release the lock
 * on a trust anchor and look it up again to delete it.
 */
struct val_anchors {
	/** lock on trees */
	lock_basic_t lock;
	/**
	 * Anchors are store in this tree. Sort order is chosen, so that
	 * dnames are in nsec-like order. A lookup on class, name will return
	 * an exact match of the closest match, with the ancestor needed.
	 * contents of type trust_anchor.
	 */
	rbtree_t* tree;
	/** The DLV trust anchor (if one is configured, else NULL) */
	struct trust_anchor* dlv_anchor;
	/** Autotrust global data, anchors sorted by next probe time */
	struct autr_global_data* autr;
};

/**
 * Trust anchor key
 */
struct ta_key {
	/** next in list */
	struct ta_key* next;
	/** rdata, in wireformat of the key RR. starts with rdlength. */
	uint8_t* data;
	/** length of the rdata (including rdlength). */
	size_t len;
	/** DNS type (host format) of the key, DS or DNSKEY */
	uint16_t type;
};

/**
 * A trust anchor in the trust anchor store.
 * Unique by name, class.
 */
struct trust_anchor {
	/** rbtree node, key is this structure */
	rbnode_t node;
	/** lock on the entire anchor and its keys; for autotrust changes */
	lock_basic_t lock;
	/** name of this trust anchor */
	uint8_t* name;
	/** length of name */
	size_t namelen;
	/** number of labels in name of rrset */
	int namelabs;
	/** the ancestor in the trustanchor tree */
	struct trust_anchor* parent;
	/**
	 * List of DS or DNSKEY rrs that form the trust anchor.
	 */
	struct ta_key* keylist;
	/** Autotrust anchor point data, or NULL */
	struct autr_point_data* autr;
	/** number of DSs in the keylist */
	size_t numDS;
	/** number of DNSKEYs in the keylist */
	size_t numDNSKEY;
	/** the DS RRset */
	struct ub_packed_rrset_key* ds_rrset;
	/** The DNSKEY RRset */
	struct ub_packed_rrset_key* dnskey_rrset;
	/** class of the trust anchor */
	uint16_t dclass;
};

/**
 * Create trust anchor storage
 * @return new storage or NULL on error.
 */
struct val_anchors* anchors_create(void);

/**
 * Delete trust anchor storage.
 * @param anchors: to delete.
 */
void anchors_delete(struct val_anchors* anchors);

/**
 * Process trust anchor config.
 * @param anchors: struct anchor storage
 * @param cfg: config options.
 * @return 0 on error.
 */
int anchors_apply_cfg(struct val_anchors* anchors, struct config_file* cfg);

/**
 * Recalculate parent pointers.  The caller must hold the lock on the
 * anchors structure (say after removing an item from the rbtree).
 * Caller must not hold any locks on trust anchors.
 * After the call is complete the parent pointers are updated and an item
 * just removed is no longer referenced in parent pointers.
 * @param anchors: the structure to update.
 */
void anchors_init_parents_locked(struct val_anchors* anchors);

/**
 * Given a qname/qclass combination, find the trust anchor closest above it.
 * Or return NULL if none exists.
 *
 * @param anchors: struct anchor storage
 * @param qname: query name, uncompressed wireformat.
 * @param qname_len: length of qname.
 * @param qclass: class to query for.
 * @return the trust anchor or NULL if none is found. The anchor is locked.
 */
struct trust_anchor* anchors_lookup(struct val_anchors* anchors,
	uint8_t* qname, size_t qname_len, uint16_t qclass);

/**
 * Find a trust anchor. Exact matching.
 * @param anchors: anchor storage.
 * @param name: name of trust anchor (wireformat)
 * @param namelabs: labels in name
 * @param namelen: length of name
 * @param dclass: class of trust anchor
 * @return NULL if not found. The anchor is locked.
 */
struct trust_anchor* anchor_find(struct val_anchors* anchors,
	uint8_t* name, int namelabs, size_t namelen, uint16_t dclass);

/**
 * Store one string as trust anchor RR.
 * @param anchors: anchor storage.
 * @param buffer: parsing buffer, to generate the RR wireformat in.
 * @param str: string.
 * @return NULL on error.
 */
struct trust_anchor* anchor_store_str(struct val_anchors* anchors,
	struct sldns_buffer* buffer, const char* str);

/**
 * Get memory in use by the trust anchor storage
 * @param anchors: anchor storage.
 * @return memory in use in bytes.
 */
size_t anchors_get_mem(struct val_anchors* anchors);

/** compare two trust anchors */
int anchor_cmp(const void* k1, const void* k2);

/**
 * Add insecure point trust anchor.  For external use (locks and init_parents)
 * @param anchors: anchor storage.
 * @param c: class.
 * @param nm: name of insecure trust point.
 * @return false on alloc failure.
 */
int anchors_add_insecure(struct val_anchors* anchors, uint16_t c, uint8_t* nm);

/**
 * Delete insecure point trust anchor.  Does not remove if no such point.
 * For external use (locks and init_parents)
 * @param anchors: anchor storage.
 * @param c: class.
 * @param nm: name of insecure trust point.
 */
void anchors_delete_insecure(struct val_anchors* anchors, uint16_t c,
	uint8_t* nm);

#endif /* VALIDATOR_VAL_ANCHOR_H */


text:
package org.wso2.carbon.identity.sso.saml.cache;

import org.wso2.carbon.base.MultitenantConstants;
import org.wso2.carbon.identity.application.authentication.framework.store.SessionDataStore;
import org.wso2.carbon.identity.core.cache.BaseCache;
import org.wso2.carbon.identity.core.util.IdentityTenantUtil;

public class SAMLSSOParticipantCache extends BaseCache<SAMLSSOParticipantCacheKey, SAMLSSOParticipantCacheEntry> {

    private static final String CACHE_NAME = "SAMLSSOParticipantCache";
    private static volatile SAMLSSOParticipantCache instance;

    private SAMLSSOParticipantCache() {
        super(CACHE_NAME);
    }

    public static SAMLSSOParticipantCache getInstance() {
        if (instance == null) {
            synchronized (SAMLSSOParticipantCache.class) {

                if (instance == null) {
                    instance = new SAMLSSOParticipantCache();
                }
            }
        }
        return instance;
    }

    /**
     * @deprecated This method was deprecated to move SAMLSSOParticipantCache to the tenant space.
     * Use {@link #addToCache(SAMLSSOParticipantCacheKey, SAMLSSOParticipantCacheEntry, String))} instead.
     */
    @Deprecated
    public void addToCache(SAMLSSOParticipantCacheKey key, SAMLSSOParticipantCacheEntry entry) {

        // For backward compatibility, SUPER_TENANT_DOMAIN was used as the cache maintaining tenant.
        addToCache(key, entry, MultitenantConstants.SUPER_TENANT_DOMAIN_NAME);
    }

    /**
     * Adds Session Information to the cache and session data store.
     *
     * @param key                Key which cache entry is indexed.
     * @param entry              SAMLSSOParticipant Cache Entry.
     * @param loginTenantDomain  Login Tenant Domain where cache will add.
     */
    @Override
    public void addToCache(SAMLSSOParticipantCacheKey key, SAMLSSOParticipantCacheEntry entry,
                           String loginTenantDomain) {

        String tenantDomain = resolveCacheTenantDomain(loginTenantDomain);
        super.addToCache(key, entry, tenantDomain);
        SessionDataStore.getInstance().storeSessionData(key.getSessionIndex(), CACHE_NAME, entry);
    }

    /**
     * @deprecated This method was deprecated to move SAMLSSOParticipantCache to the tenant space.
     * Use {@link #getValueFromCache(SAMLSSOParticipantCacheKey, String))} instead.
     */
    @Deprecated
    public SAMLSSOParticipantCacheEntry getValueFromCache(SAMLSSOParticipantCacheKey key) {

        // For backward compatibility, SUPER_TENANT_DOMAIN was used as the cache maintaining tenant.
        return getValueFromCache(key, MultitenantConstants.SUPER_TENANT_DOMAIN_NAME);
    }

    /**
     * Retrieve the session information from the cache.
     * At a cache miss data is loaded from the Session DataStore Store
     *
     * @param key                SAMLSSOParticipantCacheKey Key which cache entry is indexed.
     * @param loginTenantDomain  Login Tenant Domain.
     * @return Cache entry
     */
    @Override
    public SAMLSSOParticipantCacheEntry getValueFromCache(SAMLSSOParticipantCacheKey key, String loginTenantDomain) {

        String tenantDomain = resolveCacheTenantDomain(loginTenantDomain);
        SAMLSSOParticipantCacheEntry cacheEntry = super.getValueFromCache(key, tenantDomain);
        if (cacheEntry == null) {
            cacheEntry = (SAMLSSOParticipantCacheEntry) SessionDataStore.getInstance().
                    getSessionData(key.getSessionIndex(), CACHE_NAME);
        }
        return cacheEntry;
    }

    /**
     * @deprecated This method was deprecated to move SAMLSSOParticipantCache to the tenant space.
     * Use {@link #clearCacheEntry(SAMLSSOParticipantCacheKey, String))} instead.
     */
    @Deprecated
    public void clearCacheEntry(SAMLSSOParticipantCacheKey key) {

        // For backward compatibility, SUPER_TENANT_DOMAIN was used as the cache maintaining tenant.
        clearCacheEntry(key, MultitenantConstants.SUPER_TENANT_DOMAIN_NAME);
    }

    /**
     * Clears the Session Information from the cache and remove from session data store.
     *
     * @param key                 Key to clear cache.
     * @param loginTenantDomain   Login Tenant Domain where cache was added.
     */
    @Override
    public void clearCacheEntry(SAMLSSOParticipantCacheKey key, String loginTenantDomain) {

        String tenantDomain = resolveCacheTenantDomain(loginTenantDomain);
        super.clearCacheEntry(key, tenantDomain);
        SessionDataStore.getInstance().clearSessionData(key.getSessionIndex(), CACHE_NAME);
    }

    /**
     * Return the tenant domain where the cache needed to be maintain.
     *
     * @param tenantDomain login tenant domain.
     * @return tenantDomain Tenant Domain where the cache needed to be maintain.
     */
    private String resolveCacheTenantDomain(String tenantDomain) {

        // If tenanted sessions are not enabled, maintain caches in the super tenant domain.
        if (!IdentityTenantUtil.isTenantedSessionsEnabled()) {
            return MultitenantConstants.SUPER_TENANT_DOMAIN_NAME;
        }
        return tenantDomain;
    }

}


text:
<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of DefinationController
 *
 * @author Suchandan
 * @property Model_defination $Model_defination Model_defination
 */
class DefinationController extends MY_Controller {

    public function __construct() {

        parent::__construct();

        $this->auth(admin_base_url('login'));

        $this->loadS_model('defination');
        $this->setViewData('title', "Definations");
        $this->setViewData('view_data', array());
    }

    public function places() {

        $this->setViewData('panel_heading_country', "Country info");
        $this->setViewData('panel_heading_state', "State info");
        $this->setViewData('panel_heading_city', "City info");

        $this->setViewData('action', "insert");

        $this->setViewData('states', key_value_pair($this->Model_defination->get_states(), 'id', 'name'));
        $this->setViewData('countries', key_value_pair($this->Model_defination->get_countries(), 'id', 'name'));
        $this->add_auto_load_script('place', true);
        $this->render_view('country-city-state', 'defination');
    }

    public function listplaces() {

        $cities = array(
            'object' => 'city',
            'box_header' => "List cities",
            'list_headers' => array(
                'name' => 'Name',
                'country_name' => 'Country',
                'state_name' => 'State',
                'action' => 'Action'
            ),
            'js_sort' => true,
            'list' => $this->get_formated_list($this->Model_defination->get_cities(), 'city')
        );
        $states = array(
            'object' => 'state',
            'box_header' => "List States",
            'list_headers' => array(
                'name' => 'Name',
                'country_name' => 'Country',
                'action' => 'Action'
            ),
            'js_sort' => true,
            'list' => $this->get_formated_list($this->Model_defination->get_states(), 'state')
        );
//        $countries = array(
//            'object' => 'country',
//            'box_header' => "List country",
//            'list_headers' => array(
//                'name' => 'Name',
//                'code' => 'Code',
//                'action' => 'Action'
//            ),
//            'js_sort' => true,
//            'list' => $this->get_formated_list($this->Model_defination->get_countries(), 'country')
//        );

        $this->setViewData('city_list', $cities);
//        $this->setViewData('country_list', $countries);
        $this->setViewData('state_list', $states);
        $this->add_auto_load_script('place', true);
        $this->render_view('list-place', 'defination');
    }

    private function get_formated_list($list, $type = '') {
        if ($list) {
            foreach ($list as $key => $data) {
                $list[$key]['action'] = '';
                $list[$key]['action'] .= '

                        ';
            }
        }
        return $list;
    }

    public function ratecard($id = '') {

        $this->loadS_model('common');
        $this->loadS_model('defination');

        $this->setViewData('box_header', "Ratecard");
        $this->setViewData('object', "ratecard");
        $this->setViewData('rate_card', array());
        $this->setViewData('action', 'insert');
        if ($id) {
            $this->setViewData('action', 'update');
        }
        $this->setViewData('list_headers', array(
            "city" => 'City',
            "special_type" => 'Special Type',
            "size" => 'Tonnage',
            "mode" => 'Mode',
            "mode_unit" => 'Unit',
            "mode_unit_cost" => 'cost',
            "waiting_hour_unit" => 'Wating hour',
            "wating_hour_cost" => 'Wating hour cost',
            "free_wating_time" => 'Free wating time',
            "km_limit" => 'KM limit',
            "additional_km_unit" => 'Additional KM unit',
            "additional_km_cost" => 'Additional KM unit cost',
            "special_type_multiplier" => 'Special type multiplier',
            "labour_rate" => 'Labour rate',
            "action" => 'Action'
        ));
        if ($this->request('action') == 'insert') {
            $rate_card = $this->request('rate_card');
            if ($this->Model_common->getData(TBL_RATE_CARD, array_make(array('city', 'special_type', 'size', 'mode'), $rate_card))) {
                $this->updateRecord(TBL_RATE_CARD, array('id' => $id), $rate_card);
                $this->set_success_responce("The rate card has been updated.");
                return;
            }
            $this->insertRecord(TBL_RATE_CARD, $rate_card);
            $this->set_success_responce("The rate card has been saved.");
            return;
        } elseif ($this->request('action') == 'update') {
            $rate_card = $this->request('rate_card');
            $this->updateRecord(TBL_RATE_CARD, array('id' => $id), $rate_card);
            $this->set_success_responce("The rate card has been updated.");
            return;
        }
        $this->process_ratecard($id);
//        $this->debug_view(true);
        $this->render_view('ratecard', 'defination');
    }

    private function process_ratecard($id = '') {

        $action = 'insert';
        if ($id) {
            $rate_cards = $this->Model_common->getData(TBL_RATE_CARD, array('id' => $id));
            $action = 'update';
        }

        $rate_card_array = array();

        $cities = $this->Model_defination->get_cities();
        $rate_card_array['city'] = form_dropdown('rate_card[city]', key_value_pair($cities, 'id', 'name', array('' => "Select city")), (isset($rate_cards['city']) ? $rate_cards['city'] : ''), 'required');

        $cities = $this->Model_defination->getDatas(TBL_SPECIAL_TYPE_MASTER);
        $rate_card_array['special_type'] = form_dropdown('rate_card[special_type]', key_value_pair($cities, 'id', 'name', array('' => "Select special type")), (isset($rate_cards['special_type']) ? $rate_cards['special_type'] : ''), 'required');

        $cities = $this->Model_defination->getDatas(TBL_TONNAGE_MASTER);
        $rate_card_array['size'] = form_dropdown('rate_card[size]', key_value_pair($cities, 'id', 'name', array('' => "Select size")), (isset($rate_cards['size']) ? $rate_cards['size'] : ''), 'required');

        $rate_card_array['mode'] = form_dropdown('rate_card[mode]', array(1 => "KM Based"), (isset($rate_cards['mode']) ? $rate_cards['mode'] : ''), 'required');
        $rate_card_array['mode_unit'] = form_input('rate_card[mode_unit]', (isset($rate_cards['mode_unit']) ? $rate_cards['mode_unit'] : ''), '');
        $rate_card_array['mode_unit_cost'] = form_input('rate_card[mode_unit_cost]', (isset($rate_cards['mode_unit_cost']) ? $rate_cards['mode_unit_cost'] : ''), '');
        $rate_card_array['waiting_hour_unit'] = form_input('rate_card[waiting_hour_unit]', (isset($rate_cards['waiting_hour_unit']) ? $rate_cards['waiting_hour_unit'] : ''), '');
        $rate_card_array['wating_hour_cost'] = form_input('rate_card[wating_hour_cost]', (isset($rate_cards['wating_hour_cost']) ? $rate_cards['wating_hour_cost'] : ''), '');
        $rate_card_array['free_wating_time'] = form_input('rate_card[free_wating_time]', (isset($rate_cards['free_wating_time']) ? $rate_cards['free_wating_time'] : ''), '');
        $rate_card_array['km_limit'] = form_input('rate_card[km_limit]', (isset($rate_cards['km_limit']) ? $rate_cards['km_limit'] : ''), '');
        $rate_card_array['additional_km_unit'] = form_input('rate_card[additional_km_unit]', (isset($rate_cards['additional_km_unit']) ? $rate_cards['additional_km_unit'] : ''), '');
        $rate_card_array['additional_km_cost'] = form_input('rate_card[additional_km_cost]', (isset($rate_cards['additional_km_cost']) ? $rate_cards['additional_km_cost'] : ''), '');
        $rate_card_array['special_type_multiplier'] = form_input('rate_card[special_type_multiplier]', (isset($rate_cards['special_type_multiplier']) ? $rate_cards['special_type_multiplier'] : ''), '');
        $rate_card_array['labour_rate'] = form_input('rate_card[labour_rate]', (isset($rate_cards['labour_rate']) ? $rate_cards['labour_rate'] : ''), '');

        $rate_card_array['action'] = '';
        $rate_card_array['action'] .= form_hidden('action', $action, '');
        $rate_card_array['action'] .= form_submit('submit', 'Save', 'class="btn btn-primary"');

        $this->setViewData('rate_card', $rate_card_array);
    }

    public function ratecard_list() {
        $this->loadS_model('defination');
        $this->setViewData('box_header', "Rate Crad list");
        $this->setViewData('object', "ratecard");
        $this->setViewData('list', $this->Model_defination->get_rate_card_list());
        $this->setViewData('list_headers', array(
            "city_name" => 'City',
            "spl_type_name" => 'Special Type',
            "size_name" => 'Tonnage',
            "mode" => 'Mode',
            "mode_unit" => 'Unit',
            "mode_unit_cost" => 'cost',
            "waiting_hour_unit" => 'Wt. hour unit',
            "wating_hour_cost" => 'Wt. hour cost',
            "free_wating_time" => 'Free wt. time',
            "km_limit" => 'KM limit',
            "additional_km_unit" => 'Addl KM unit',
            "additional_km_cost" => 'Addl KM unit cost',
            "special_type_multiplier" => 'Spl type multiplier',
            "labour_rate" => 'Labour rate',
            "action" => 'Action'
        ));

        $this->get_formated_rate_card_list();
        $this->render_view('list', 'common');
    }

    private function get_formated_rate_card_list() {
        $list = $this->getViewData('list');
        if ($list) {
            foreach ($list as $key => $user) {
                $list[$key]['action'] = '';
                $list[$key]['action'] .= $this->load->view('common/action-bar', array_merge($user, array(
                    'no_view' => true,
                    'edit_url' => "ratecard/{$user['id']}",
                    'delete_url' => "rate_card_delete/{$user['id']}",
                    'no_view' => true,
                        )), true);
//                $list[$key]['status'] = ($user['status']) ? 'Active' : 'Inactive';
            }
            $this->setViewData('list', $list);
        }
    }

    public function rate_card_delete($id = '') {
        if ($id) {
            $this->loadS_model('defination');
            $this->Model_defination->deleteRecord(TBL_RATE_CARD, array('id' => $id));
        }
        $this->redirectTO(admin_base_url('define/ratecard_list'), "The rate card successfully deleted.");
    }

    public function special_type() {

        $this->setViewData('box_header', "Special Type");
        $this->setViewData('object', "special-type");
        $this->setViewData('box_id', "special-type-box");
        $this->setViewData('list_headers', array(
            'id' => 'ID',
            'name' => 'Name',
            'action' => 'Action'
        ));

        $this->loadS_model('defination');
        $this->setViewData('list', $this->Model_defination->getDatas(TBL_SPECIAL_TYPE_MASTER));
        $this->get_formated_spl_type_list();
        $this->add_auto_load_script('special_type', true);
        $this->render_view('list', 'common');
    }

    private function get_formated_spl_type_list() {

        $list = $this->getViewData('list');
        if ($list) {
            foreach ($list as $key => $user) {
                $list[$key]['action'] = '';
                $list[$key]['name'] = '' . $user['name'] . '';
                $list[$key]['name'] .= form_input('spl_name', $user['name'], 'class="hideme"');
                $list[$key]['action'] .= $this->load->view('common/action-bar', array_merge($user, array(
                    'no_view' => true,
                    'no_delete' => true,
                    'edit_url' => "#",
                    'delete_url' => "#",
                    'save_me' => true,
                    'save_class' => 'hideme',
                    'save_url' => base_url('ajax/save_spltype'),
                    'cancel_me' => true,
                    'cancel_class' => 'hideme',
                    'cancel_url' => '#'
                        )), true);
            }
            $this->setViewData('list', $list);
        }
    }

    public function timeframes() {

        $this->setViewData('box_header', "Timeframe");
        $this->setViewData('object', "timeframe");
        $this->setViewData('box_id', "timeframe-box");
        $this->setViewData('list_headers', array(
            'id' => 'ID',
            'start' => 'Start (Hr)',
            'end' => 'End (Hr)',
            'discount' => 'Discount',
            'action' => 'Action'
        ));

        $this->loadS_model('defination');
        $this->setViewData('list', $this->Model_defination->getDatas(TBL_TIMEFRAME_MASTER));
        $this->get_formated_timeframes_list();
        $this->add_auto_load_script('timeframe', true);
        $this->render_view('list', 'common');
    }

    private function get_formated_timeframes_list() {

        $list = $this->getViewData('list');
        if ($list) {
            foreach ($list as $key => $user) {
                $list[$key]['action'] = '';
//                debug($user);
                $list[$key]['start'] = '' . date('h', strtotime($user['start'])) . '';
                $list[$key]['start'] .= form_input('time[start]', date('h', strtotime($user['start'])), 'class="hideme inputter"');

                $list[$key]['end'] = '' . date('h', strtotime($user['end'])) . '';
                $list[$key]['end'] .= form_input('time[end]', date('h', strtotime($user['end'])), 'class="hideme inputter"');

                $list[$key]['discount'] = '' . $user['discount'] . '';
                $list[$key]['discount'] .= form_input('time[discount]', $user['discount'], 'class="hideme inputter"');

                $list[$key]['action'] .= $this->load->view('common/action-bar', array_merge($user, array(
                    'no_view' => true,
                    'no_delete' => true,
                    'edit_url' => "#",
                    'delete_url' => "#",
                    'save_me' => true,
                    'save_class' => 'hideme',
                    'save_url' => base_url('ajax/save_timeframe'),
                    'cancel_me' => true,
                    'cancel_class' => 'hideme',
                    'cancel_url' => '#'
                        )), true);
            }
            $this->setViewData('list', $list);
        }
    }

    public function tonnege() {

        $this->setViewData('box_header', "Tonnege");
        $this->setViewData('object', "tonege");
        $this->setViewData('box_id', "tonege-box");
        $this->setViewData('action_url', '');

        $this->loadS_model('defination');

        if ($this->request('submit_tonnege')) {
            $ton = $this->request('tonnege');
            $name = "{$ton['min']}-{$ton['max']}";
            $id = $this->Model_defination->insertRecord(TBL_TONNAGE_MASTER, array('name' => $name));
            $this->setData('object', array('id' => $id, 'name' => $name));
            $this->set_success_responce("The tonnege successfully saved.");
            return;
        }

        $key_header = $object_data = array(
            'min' => 'Min',
            'max' => 'Max',
            'action' => 'Action',
        );
        $object_data['min'] = form_number('tonnege[min]', '');
        $object_data['max'] = form_number('tonnege[max]', '');
        $object_data['action'] = form_submit('sbmit', 'Save', 'class="btn btn-primary"') . form_hidden('submit_tonnege', 1);

        $this->setViewData('key_headers', $key_header);

        $this->setViewData('list_headers', array(
            'id' => 'ID',
            'name' => 'Name',
            'action' => "Action"
        ));
        $this->setViewData('object_data', $object_data);

        $this->loadS_model('defination');

        $this->setViewData('list', $this->Model_defination->getDatas(TBL_TONNAGE_MASTER));
        $this->add_auto_load_script('tonnage', true);
        $this->get_formated_tonnage();
        $this->render_view(array('register-template' => 'common', 'list' => 'common'));
    }

    private function get_formated_tonnage() {

        $list = $this->getViewData('list');
        if ($list) {
            foreach ($list as $key => $user) {
                $list[$key]['action'] = '';
                $list[$key]['action'] .= $this->load->view('common/action-bar', array_merge($user, array(
                    'no_view' => true,
                    'no_edit' => true,
                    'delete_url' => base_url('ajax/delete_ton?id=' . $user['id'])
                        )), true);
            }
            $this->setViewData('list', $list);
        }
    }

}


text:
class Stage {
private:
  Map map;
  Tileset tileset;
public:
  Stage();
  ~Stage();
  //! Create a stage by passing in a Map and Tileset.
  void createStage(Map m, Tileset t) { setMap(m); setTileset(t); }
  //! Create a stage by passing in the maps file, a name for the tiles, file of the tile image, the renderer, width and height of a tile, what row of the image the tiles are onem and how many tiles there are.
  void createStage(string filename, string name, string img, SDL_Renderer* ren, int width, int height, int r, int count);
  void createStage(string filename, string name, string img, SDL_Renderer* ren, int width, int height, int r, int rcount, int count);
  void createStage(string filename, int startid, string name, string img, SDL_Renderer* ren, int width, int height, int r, int count);
  void createStage(string filename, int startid, string name, string img, SDL_Renderer* ren, int width, int height, int r, int rcount, int count);
  //! Set the Map by passing in a Map.
  void setMap(Map m) { map = m; }
  //! Load in a new map by passing in the map file.
  Map setMap(string filename) { map.loadMap(filename); return map; }
  //! Get the Map.
  Map getMap() const { return map; }
  //! Set the Tileset with a given Tileset.
  void setTileset(Tileset t) { tileset = t; }
  Tileset setTileset(string name, string img, SDL_Renderer* ren, int width, int height, int r, int count);
  Tileset setTileset(string name, string img, SDL_Renderer* ren, int width, int height, int r, int rcount, int count);
  Tileset setTileset(int startid, string name, string img, SDL_Renderer* ren, int width, int height, int r, int count);
  Tileset setTileset(int startid, string name, string img, SDL_Renderer* ren, int width, int height, int r, int rcount, int count);
  //! Get the Tileset.
  Tileset getTileset() const { return tileset; }
};

#endif //STAGE_H


text:
function main_fit
%{
========================================
Created by: Chris Cadonic
For: M.Sc program in Biomedical Engineering
Project: Modeling Mitochondrial Bioenergetics
========================================
This is the primary file for running the mitochondrial model created
for my master's project as part of the biomedical engineering
program.

See the readme file 'manual.pdf' for more information as to how
this program functions and how each component script functions.
The readme file 'changelog.txt' indicates the changes implemented
into the model as well as the timestamps for each change.

This code is slightlty altered from its original form to simply model
the decoupled system, that is, to primarily model complex IV.

For altering the parameters of the model, changes can be made to
the differential equations in 'decoupled_derivative_system.m', the
setup conditions in 'setup.m', optimization run by using
'launchQubist.m', the gui handled by 'main_gui.m', and the
importing of data handled by 'data_formatter.m'.
%}

parameters = setup; %run the setup function which creates the
%structure storing all variables necessary
%for the model (found in 'setup.m')

save parameters %save the model parameters in parameters.mat

%create the GUI for interfacing and display
%finalgui(parameters);

% Since we are fitting data
finalgui_fit(parameters, 1); % 1 for ctrl Data, 2 for exp Data


text:
from django import test
from django import template

from pseudo_cms import models

__all__ = ('PageContentTagTests', )

class PageContentTagTests(test.TestCase):
    def test_adds_page_content_to_context(self):
        url = "/path/to/something/"
        content = models.Content.objects.create(url=url, title="My Title")

        t = template.Template(
            """{% load pseudo_cms_tags %}{% page_content path as content %}

{{ content.title }}

        """)
        result = t.render(template.Context({'path': url}))

        self.assertHTMLEqual("
{0.title}
".format(content), result)


text:
This is a project that aims to enhance the **appearance**, **usability** and **functionality** of the dorm administration page.

## Why

The origin PHP implementation [dorm.ntu.edu.tw](dorm.ntu.edu.tw) can functions very well.
From user registration, MRTG display, blacklist rendering to administrative tools, the functionality of this
implementation works the way it ought to be.  Yet, being a administrator, a everyday user of this site myself,
I think there's much to be desired.  I will briefly explain why I think it worths a rewrite.

### Appearance

In a pragmatic point of view, appearance does not really matters.  But it's always the most obviously place for
enhancement.  I believe everyone will agree to switch to a more modern, slick interface.

### User Interface

**This is the most important criteria**, yet it happens to be the most criticized aspect of the current site.
Some students complain that the registration page makes it difficult for them to decide which fields to fill out.
Being an adminstrator myself, I find it hard to scroll through the mal-designed IP blacklist.  In addition, the
table simply contains too much unnecessary information.  The naming of the navigation bar is **unsemantic** and **redundant**, making it hard to see which functionality it points to.  The network flow rank is **full of number**, which hardly provides any intuition (the correct way is to visualize it in a graph).  The block list provides little information on the reason why an IP shall be blocked.

### Not responsive

The current webpage is a disaster on mobile device!!  As network administrator, I often carry smart phone to look up IPs on this site when I'm out repairing people's network.  This is simply a nightmare.

### Bad tutorial

There is actually a tutorial on how to fix network problems on [dorm.ntu.edu.tw](dorm.ntu.edu.tw), but **few people know**.  Even if they're led to [here](http://dorminfo.cc.ntu.edu.tw/), the tutorial does not contain the necessary information to fix their problems.  They're unintuitive and outdated.  We shall make it easier to find tutorials  and populate the tutorial with more scenario ( it can be contributed by network admins from all over the campus ), in a way that **even my grandma** can fix her network problems in our guidance.
We can even provide scripts that automatically detect the user's problems and fix it for them.

### Authorization Account Management

Being a M1 network administrator, I was given an account of `m1.ntu.edu.tw`, with a predefined password
when I started my job, as if I was passed along a key that had been used for many generations.
This is a very **insecure** approach to hand over administratory rights.  The more reasonable way is to delete
the old account and let me register a new admin account.

## How it can be improved

### Frontend / backend sepearation

The current PHP implementation bundles PHP script along with backend service.  This unmodularized approach renders it hard to modify frontend without breaking backend logic.  In addition, this approach dooms the page to be **static** ( it cannot dynamically update content without reloading the page )  The better approach is to seperate frontend from backend.  The backend simply serves **RESTful APIs** so that the frontend can call these APIs in whatever suitable manner.  In this way, conforming to the same interface, we can modify both backend and frontend **without breaking each other**.
( we prefer this approach because we don't want to rewrite the whole application when we want to adopt to new technology / new appearance or any server failures )
This is also a more scalable approach because you can distribute frontend and backend to different servers.

### The user should be notified

The user will never know why his network cannot function.  If his network is in fact blocked by [cc.ntu.edu.tw](cc.ntu.edu.tw), he should be notified immediately by email or other means ( such as Facebook message, which I'll explain in the next section ) so that he can take the necessary steps as soon as possible.  This saves both his and network administrators' time.  **( This issue is very critical!! )**

### Facebook integration

**Everyone uses Facebook**.  We can integrate Facebook Oauth so that we can notify users through Facebook messages.  This is **the fastest way a user could be notified**.

### Coherent way to request a repair

In the case of first-man dorm, users request a repair on a Google Spreadsheet in our Facebook Group.  But some
people are simply not a member of that group, still more people never know they can make such request on that group.  We can integrate a repair request page into our website so the user knows where to make such request.  In
addition, they can make a request even without external network access.

### Personalized MRTG statistics

A user would definitely be glad to know his own network flow statistics, just like Google's custom activity report.  I think this is very doable, and will be a much desired feature.

## Design

### Graphics

I am not a graphic designer.  Yet being a programmer, I'm good at adopting others's work and customizing it into our liking.
I will base on the UI framework [Material Design Lite](http://www.getmdl.io/) recently released by Google and tweak it to such a manner that you and I will satisfy.  **This is responsive.** ( so that you can easily read the content on mobile device. )

### UI

#### Table

The most important UI component in our application would be **table**.  ( block list, user list, network flow rank all
rely on this component ) I will base on [Angular UI Grid](http://ui-grid.info/) which
will satisfy the following goals:

- Properly paginated.
- Easily collapsable fields to reduce unnecessary information.
- Easily searchable.
- Dynamic loaded ( without refreshing the page )

#### Statistics

[dorm.ntu.edu.tw](dorm.ntu.edu.tw) contains a lot of statistics.  But if the user cannot see the
pattern at first sight, the statistics is basically useless.  [d3.js](d3js.org) provides many
intuitive, interactive, dynamic visualizations.
By visualizing, adding interactivity to MRTG and network flow rank, we provide user a chance to know more
about the lives of other NTU students.

## Technology

#### Frontend

- [Angular.js](https://angularjs.org/)
- [Angular UI Grid](ui-grid.info/)
- [Angular OAuth](https://github.com/seegno/angular-oauth2)
- [jQuery](https://jquery.com/)
- [Material Design Lite](http://getmdl.io/)
- [Bootstrap](getbootstrap.com/)
- [d3.js](d3js.org)
- [LESS](lesscss.org)

#### Backend

- [Node.js](https://nodejs.org/)
- [Express.js](expressjs.com/)
- TBA


text:
#ifndef SDE_F_CONTROL_UPDATE_H
#define SDE_F_CONTROL_UPDATE_H

#include <memory>
#include <vector>
#include "ControlUpdate.h"

namespace adef {

class Configuration;
class PrototypeManager;
class Repository;
class Random;

/**
@brief SdeFControlUpdate updates internal states by
the procedure of F value in the SDE algorithm.

@par The configuration
SdeFControlUpdate has no extra configurations.@n
See setup() for the details.
*/
class SdeFControlUpdate : public ControlUpdate
{
public:

/// The type of the object
    using Object = double;

/**
@brief Clone the current class.
@sa clone_impl()
*/
    std::shared_ptr<SdeFControlUpdate> clone() const
    {
        return std::dynamic_pointer_cast<SdeFControlUpdate>(clone_impl());
    }
/**
@brief Set up the internal states.

If @em SomeThing is SdeFControlUpdate,@n
its configuration should be
- JSON configuration
@code
"SomeThing": {
    "classname" : "SdeFControlUpdate"
}
@endcode
.
*/
    void setup(const Configuration& config, const PrototypeManager& pm) override;

    void update(std::shared_ptr<Repository> repos,
        std::shared_ptr<BaseControlParameter> parameter,
        std::shared_ptr<BaseFunction> function) const override;

private:

    std::vector<std::size_t> exclusive_random_generator(
        std::vector<std::size_t>& used_numbers,
        unsigned int number_of_result,
        unsigned int min_range,
        unsigned int max_range,
        std::shared_ptr<Random> random) const;

private:

    std::shared_ptr<Prototype> clone_impl() const override
    {
        return std::make_shared<SdeFControlUpdate>(*this);
    }
};

}

#endif // SDE_F_CONTROL_UPDATE_H


text:
import _ from 'lodash';
import config from '../lib/config';

export const TOGGLE_CONNECT = 'TOGGLE_CONNECT';
export const LOAD_CONFIG = 'LOAD_CONFIG';

export const loadConfig = () => {
  return {type: LOAD_CONFIG, config: _.cloneDeep(config)};
};

export const toggleConnect = () => {
  config.includeConnect = !config.includeConnect;
  return {type: TOGGLE_CONNECT, includeConnect: config.includeConnect};
};


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

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:paddingLeft="15dp"
        android:paddingRight="15dp"
        android:orientation="horizontal"
        android:background="#FF94BBBD">
        <EditText
            android:id="@+id/search_edittext"
            android:layout_gravity="center_vertical"
            android:layout_width="0dp"
            android:background="@android:color/white"
            android:layout_weight="1"
            android:layout_height="30dp"
            android:hint="search"/>
        <Button
            android:id="@+id/add_inventory_item"
            android:layout_width="30dp"
            android:layout_height="30dp"
            android:layout_gravity="center_vertical"
            android:text="+"
            android:textColor="@android:color/white"
            android:layout_margin="5dp"
            android:background="@color/actionbar_color"/>
    </LinearLayout>

    <de.timroes.android.listview.EnhancedListView
        android:id="@+id/inventory_list"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>

    <RelativeLayout
        android:id="@+id/pantry_bare_view"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <TextView
            android:id="@+id/pantry_bare_textview"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="YOUR PANTRY IS LOOKING AWFULLY BARE"
            android:textColor="@color/red_textview"
            android:textSize="15sp"
            android:paddingTop="10dp"
            android:paddingBottom="10dp"
            android:gravity="center_horizontal"/>
        <LinearLayout
            android:layout_below="@id/pantry_bare_textview"
            android:layout_width="match_parent"
            android:orientation="horizontal"
            android:gravity="center_horizontal"
            android:layout_height="wrap_content">
            <Button
                android:id="@+id/add_inventory_item_too"
                android:layout_width="wrap_content"
                android:layout_height="35dp"
                android:paddingLeft="15dp"
                android:paddingRight="15dp"
                android:text="ADD ITEMS"
                android:typeface="sans"
                android:background="@color/red_textview"
                android:textColor="@android:color/white"
                android:textSize="12sp"
                android:layout_marginLeft="20dp"/>
            <Button
                android:id="@+id/update_shopping_list"
                android:layout_width="wrap_content"
                android:layout_height="35dp"
                android:textSize="12sp"
                android:typeface="sans"
                android:paddingLeft="15dp"
                android:paddingRight="15dp"
                android:background="@color/red_textview"
                android:textColor="@android:color/white"
                android:layout_marginLeft="20dp"
                android:text="UPDATE SHOPPING LIST"/>
        </LinearLayout>
    </RelativeLayout>
</LinearLayout>


text:
package org.heigit.ors.fastisochrones.partitioning;

import com.carrotsearch.hppc.IntHashSet;
import com.graphhopper.routing.util.CarFlagEncoder;
import com.graphhopper.routing.util.EncodingManager;
import com.graphhopper.storage.GraphHopperStorage;
import org.heigit.ors.util.ToyGraphCreationUtil;
import org.heigit.ors.fastisochrones.partitioning.storage.CellStorage;
import org.heigit.ors.fastisochrones.partitioning.storage.IsochroneNodeStorage;
import org.junit.Test;

import static org.junit.Assert.*;

public class PreparePartitionTest {
    private final CarFlagEncoder carEncoder = new CarFlagEncoder();
    private final EncodingManager encodingManager = EncodingManager.create(carEncoder);

    @Test
    public void testPrepareCellIds() {
        GraphHopperStorage gs = ToyGraphCreationUtil.createMediumGraph(encodingManager);
        PreparePartition partition = new PreparePartition(gs, null);
        partition.prepare();
        CellStorage cs = partition.getCellStorage();
        assertEquals(2, partition.getIsochroneNodeStorage().getCellIds().size());

        int[] cellIds = partition.getIsochroneNodeStorage().getCellIds().toArray();
        IntHashSet expectedIds0 = new IntHashSet(5);
        expectedIds0.addAll(0, 1, 2, 3, 8);
        IntHashSet expectedIds1 = new IntHashSet(4);
        expectedIds1.addAll(4, 5, 6, 7);
        assertTrue(cs.getNodesOfCell(cellIds[0]).equals(expectedIds0) && cs.getNodesOfCell(cellIds[1]).equals(expectedIds1)
                || cs.getNodesOfCell(cellIds[0]).equals(expectedIds1) && cs.getNodesOfCell(cellIds[1]).equals(expectedIds0));
    }

    @Test
    public void testPrepareBorderness() {
        GraphHopperStorage gs = ToyGraphCreationUtil.createMediumGraph(encodingManager);
        PreparePartition partition = new PreparePartition(gs, null);
        partition.prepare();
        IsochroneNodeStorage ins = partition.getIsochroneNodeStorage();

        assertFalse(ins.getBorderness(0));
        assertFalse(ins.getBorderness(1));
        assertFalse(ins.getBorderness(2));
        assertTrue(ins.getBorderness(3));
        assertTrue(ins.getBorderness(8));

        assertFalse(ins.getBorderness(5));
        assertFalse(ins.getBorderness(6));
        assertTrue(ins.getBorderness(4));
        assertTrue(ins.getBorderness(7));
    }
}


text:
using InfluxData.Net.Kapacitor.ClientModules;

namespace InfluxData.Net.Kapacitor
{
    public interface IKapacitorClient
    {
        ITaskClientModule Task { get; }
    }
}


text:
.. _provision_request:

.. automodule:: Cloudforms.managers.provision_request
    :members:
    :inherited-members:


text:
package rescala.meta

import rescala.core.{CreationTicket, Struct}

case class ObserverData[S <: Struct](onSuccess: Nothing => Unit, onFailure: Throwable => Unit, ticket: CreationTicket[S]) {
  // Prevent structural equality check for case-classes
  private class Data
  private val _data = new Data()

  override def equals(obj: scala.Any): Boolean = obj match {
    case n: ObserverData[_] => n._data == _data
    case _ => false
  }
  override def hashCode(): Int = _data.hashCode()
}

trait MetaLog[T] {
  protected[meta] val node : DataFlowRef[T]
}

case class LoggedCreate[T](override val node : DataFlowRef[T]) extends MetaLog[T]
case class LoggedDisconnect[T](override val node : DataFlowRef[T]) extends MetaLog[T]
case class LoggedSet[T](override val node : VarRef[T], value : T) extends MetaLog[T]
case class LoggedFire[T](override val node : EvtRef[T], value : T) extends MetaLog[T]
case class LoggedObserve[T, S <: Struct](override val node : DataFlowRef[T], observer : ObserverData[S]) extends MetaLog[T]


text:
.. epigraph::

  Truth cannot penetrate a closed mind. If all places in the universe are in
  the Aleph, then all stars, all lamps, all sources of light are in it, too.

  -- `The Aleph <http://www.phinnweb.org/links/literature/borges/aleph.html>`_,
  Jorge Luis Borges

**Aleph** is a tool for indexing large amounts of both documents (PDF, Word,
HTML) and structured (CSV, XLS, SQL) data for easy browsing and search. It is
built with investigative reporting as a primary use case. Aleph allows
cross-referencing mentions of well-known entities (such as people and
companies) against watchlists, e.g. from prior research or public datasets.

For further details on the software, how to use it, install it or manage data
imports, please check the documentation at:

* https://docs.alephdata.org
* Installation: https://docs.alephdata.org/developers/installation
* Changes: https://docs.alephdata.org/developers/changelog

Support
-------

Aleph is used and developed by multiple organisations and interested individuals.
If you're interested in participating in this process, please read the support
policy (`SUPPORT.md`), the contribution rules (`CONTRIBUTING.md`), and the code of conduct (`CODE_OF_CONDUCT.md`) and then get
in touch:

* https://docs.alephdata.org/get-in-touch

Release process
---------------

If you are interested in, or have been tasked with releasing a new version of Aleph. The following steps should be followed:

Overview
--------

The basic process for releasing Aleph is this:

1. Check internal libraries for updates and merge. Release our libraries in the following order
  1. servicelayer
  2. followthemoney
  3. ingest-file
  4. react-ftm
2. Ensure that all libraries for a release are up to date in aleph and merged to the develop branch.
3. Ensure that any features, bugfixes are merged into develop and that all builds are passing
4. Ensure that the CHANGELOG.md file is up to date on the develop branch. Add information as required.
5. Create a RC release of Aleph.
6. Test and verify the RC. Perform further RC releases as required.
7. Merge all changes to main
8. Create a final version of Aleph

As far as possible apply the rules of semantic versioning when determining the type of release to perform.

Technical process
-----------------

RC releases
-----------

If you need to perform an RC release of Aleph, follow these steps:

1. Ensure that the `CHANGELOG`` is up to date on the develop branch and that all outstanding PR's have been merged
2. From the develop branch run bump2version (major, minor, patch) this will create a x.x.x-rc1 version of aleph
3. push the tags to the remote with git push --tags
4. push the version bump with git push
5. If there are problems with the RC you can fix them and use bump2version build to generate new rc release

Major, minor, patch releases
----------------------------

1. switch to `main` and pull from remote
2. If not already done merge `develop` into `main`
3. Update translations using `make translate`
4. If you get npm errors, go into the ui folder and run `npm install`
5. commit translations to `main` and push to remote
6. run `bump2version release`. Note that bump2version won't show changes when you make the change, but it will work (see `git log` to check)
7. push the tags to the remote with `git push --tags`
8. push version bump to remote with `git push`
9. merge `main` back into `develop`. Slightly unrelated to the release process but this is a good time to do it so that the new version numbers appear in `develop` as well


text:
// Copyright 2007-2012 Chris Patterson, Dru Sellers, Travis Smith, et. al.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed
// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
// CONDITIONS OF ANY KIND, either express or implied. See the License for the
// specific language governing permissions and limitations under the License.
namespace Topshelf.HostConfigurators
{
    using System;
    using CommandLineParser;
    using Options;

    class CommandLineSwitchConfigurator :
        CommandLineConfigurator
    {
        readonly Action<bool> _callback;
        readonly string _name;

        public CommandLineSwitchConfigurator(string name, Action<bool> callback)
        {
            _name = name;
            _callback = callback;
        }

        public void Configure(ICommandLineElementParser<Option> parser)
        {
            parser.Add(from s in parser.Switch(_name)
                       select (Option)new ServiceSwitchOption(s, _callback));
        }

        class ServiceSwitchOption :
            Option
        {
            readonly Action<bool> _callback;
            readonly bool _value;

            public ServiceSwitchOption(ISwitchElement element, Action<bool> callback)
            {
                _callback = callback;
                _value = element.Value;
            }

            public void ApplyTo(HostConfigurator configurator)
            {
                _callback(_value);
            }
        }
    }
}


text:
<!DOCTYPE HTML>

  <title>Test for Bug 536895</title>

  <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/>

Mozilla Bug 536895

<textarea id="t"></textarea>
<input id="i" type="text">
<input id="p" type="password">


text:
use strict;

sub sql_comment {
    my ($comment) = @_;

    return "-- $comment";
}

sub sql_how_to_run_as_admin {
    my ($user_name, $outfile) = @_;

    return "mysql --local_infile=1 -v -u root < $outfile";
}

sub sql_recreate_database_and_user_to_access_it {
    my ($db_name, $user_name, $user_pwd, $db_server) = @_;

    # *Re*create, so drop old database, if any.
    my $result = "drop database if exists $db_name;\n";

    # Create database.
    $result .= "create database $db_name;\n";

    # Switch to it.
    $result .= "use $db_name;\n";

    # Create user, if not already there.
    # The grant statement will create a user if it doesn't already exist.
    # Thanks, http://bugs.mysql.com/bug.php?id=19166
    $result .= "grant all on $db_name.* to '$user_name'\@'$db_server' identified by '$user_pwd';";

    # No need to switch to this user for schema creation or data import; this user is for accessing the data only.
    # TODO: limit to specific grants rather than "all"?

    return $result;
}

sub sql_create_table_start {
    my ($table_name) = @_;

    return "create table $table_name (";
}

sub sql_create_table_end {
    return ");";
}

sub sql_datatype_def {
    my ($type, $size, $is_unsigned) = @_;

    if ($type eq "Numeric") {
        my $result;
        if ($size =~ /\./) {
            $result = "dec(" . join(", ", split /\./, $size) . ")";
        } elsif ($size <= 2) {
            $result = "tinyint($size)";
        } elsif ($size <= 4) {
            $result = "smallint($size)";
        } elsif ((!$is_unsigned and $size <= 6) or ($is_unsigned and $size <= 7)) {
            $result = "mediumint($size)";
        } elsif ($size <= 9) {
            $result = "int($size)";
        } else {
            $result = "bigint($size)";
        }
        $result .= " unsigned" if $is_unsigned;
        return $result;
    } elsif ($type eq "Alphanumeric") {
        return "varchar($size)";
    } elsif ($type =~ /^Date/) {
        return "date";
    } else {
        die "Unexpected data type $type";
    }
}

sub sql_field_def {
    my ($field_name, $datatype, $allows_null) = @_;

    return "$field_name $datatype" . ($allows_null ? "" : " not null");
}

sub sql_insert {
    my ($table_name, %field_names_and_values) = @_;
    my @field_names = ();
    my @field_values = ();

    foreach my $key (keys %field_names_and_values) {
        push @field_names, $key;
        push @field_values, $field_names_and_values{$key};
    }

    return "insert into $table_name (" . join(", ", @field_names) . ") values ('" . join("', '", @field_values) . "');";
}

sub sql_convert_empty_string_to_null {
    my ($table_name, $field_name) = @_;

    return "UPDATE $table_name SET $field_name = NULL WHERE $field_name = '';";
}

sub sql_convert_to_uppercase {
    my ($table_name, $field_name) = @_;

    return "UPDATE $table_name SET $field_name = UPPER($field_name);";
}

sub sql_add_primary_keys {
    my ($table_name, @field_names) = @_;

    return "alter table $table_name add primary key (" . join(", ", @field_names) . ");";
}

sub sql_add_foreign_key {
    my ($table_name, $field_name, $foreign_key) = @_;

    return "alter table $table_name add foreign key ($field_name) references " . join("(", split /\./, $foreign_key) . ");";
}

sub sql_dateformat {
    my ($format) = @_;

    $format =~ s/mm/%m/;
    $format =~ s/dd/%d/;
    $format =~ s/yyyy/%Y/;

    return $format;
}

sub sql_load_file {
    my ($nutdbid, $user_name, $user_pwd, $file, $table_name, $field_separator, $text_separator, $line_separator, $ignore_header_lines, @fieldinfo) = @_;

    # TODO: how to make MySQL generate an error if varchar data truncation occurs?
    my $relative_file = join("", split /\.\/$nutdbid\/dist/, $file);
    my $result = "load data local infile '$relative_file'\n";
    $result .= "    into table $table_name\n";
    $result .= "    fields terminated by '$field_separator'";
    $result .= " optionally enclosed by '$text_separator'" if $text_separator;
    $result .= "\n";
    $result .= "    lines terminated by '$line_separator'\n";
    $result .= "    ignore $ignore_header_lines lines\n" if $ignore_header_lines;
    $result .= "    (";

    # Specify field order and convert dates.
    my $saw_one = 0;
    my @date_vars = ();
    foreach (@fieldinfo) {
        $result .= ", " if $saw_one;
        $saw_one = 1;

        my %info = %{$_};
        if ($info{"type"} =~ m/^Date/) {
            $info{"type"} =~ s/Date\(//;
            $info{"type"} =~ s/\)//;
            push @date_vars, { "name" => $info{"name"}, "format" => sql_dateformat($info{"type"}) };

            $result .= "\@date" . ($#date_vars + 1);
        } else {
            $result .= $info{"name"};
        }
    }
    $result .= ")\n";

    # Output date assignments, if any.
    $result .= "    set\n" if $#date_vars >= 0;
    my $idx = 1;
    my $saw_one = 0;
    foreach (@date_vars) {
        $result .= ",\n" if $saw_one;
        $saw_one = 1;

        my %info = %{$_};
        $result .= "    " . $info{"name"} . " = str_to_date(\@date$idx, '" . $info{"format"} . "')";
        $idx += 1;
    }

    # Finish command.
    $result .= ";";
    return $result;
}

sub sql_assert_record_count {
    my ($table_name, $record_count) = @_;

    # MySQL (versions <= 5.5 at least) does not support assertions, so do this via a workaround.
    # 1. create a temporary table with a single unique numeric field
    # 2. insert the value 2
    # 3. insert the record count of the table to be asserted
    # 4. remove the record where the value is the assertion value
    # case a: if the record count in step 3 == assertion value, there's now just 1 row in the temporary table (just the value 2)
    # case b: if the record count in step 3 != assertion value, there are now 2 rows in the temporary table (the value 2 and the incorrect record count value)
    # 5. insert the record count of the temporary table
    # no error for case a, and a sql error for case b (trying to insert a non-unique value)
    # (note this also works if the assertion value happens to == 2)

    my $result = "create table tmp (c int unique key);\n";
    $result .= "insert into tmp (c) values (2);\n";
    $result .= "insert into tmp (select count(*) from $table_name);\n";
    $result .= "delete from tmp where c = $record_count;\n";
    $result .= "insert into tmp (select count(*) from tmp);\n";
    $result .= "drop table tmp;";
    return $result;
}

1;


text:
import pandas

df = pandas.read_csv('sample.csv')

# Any missing values?
print df['Price']
print df['Description']

# Fill missing prices by a linear interpolation
df['Description'] = df['Description'].fillna("No description is available.")
df['Price'] = df['Price'].interpolate()

print df


text:
$script:dscModuleName = 'ActiveDirectoryDsc'
$script:dscResourceFriendlyName = 'WaitForADDomain'
$script:dscResourceName = "MSFT_$($script:dscResourceFriendlyName)"

try
{
    Import-Module -Name DscResource.Test -Force -ErrorAction 'Stop'
}
catch [System.IO.FileNotFoundException]
{
    throw 'DscResource.Test module dependency not found. Please run ".\build.ps1 -Tasks build" first.'
}

$script:testEnvironment = Initialize-TestEnvironment `
    -DSCModuleName $script:dscModuleName `
    -DSCResourceName $script:dscResourceName `
    -ResourceType 'Mof' `
    -TestType 'Integration'

try
{
    $configFile = Join-Path -Path $PSScriptRoot -ChildPath "$($script:dscResourceName).config.ps1"
    . $configFile

    Describe "$($script:dscResourceName)_Integration" {
        BeforeAll {
            $resourceId = "[$($script:dscResourceFriendlyName)]Integration_Test"
        }

        $configurationName = "$($script:dscResourceName)_WaitDomainControllerCurrentUser_Config"

        Context ('When using configuration {0}' -f $configurationName) {
            It 'Should compile and apply the MOF without throwing' {
                {
                    $configurationParameters = @{
                        OutputPath        = $TestDrive
                        # The variable $ConfigurationData was dot-sourced above.
                        ConfigurationData = $ConfigurationData
                    }

                    & $configurationName @configurationParameters

                    $startDscConfigurationParameters = @{
                        Path         = $TestDrive
                        ComputerName = 'localhost'
                        Wait         = $true
                        Verbose      = $true
                        Force        = $true
                        ErrorAction  = 'Stop'
                    }

                    Start-DscConfiguration @startDscConfigurationParameters
                } | Should -Not -Throw
            }

            It 'Should be able to call Get-DscConfiguration without throwing' {
                {
                    $script:currentConfiguration = Get-DscConfiguration -Verbose -ErrorAction Stop
                } | Should -Not -Throw
            }

            It 'Should have set the resource and all the parameters should match' {
                $resourceCurrentState = $script:currentConfiguration | Where-Object -FilterScript {
                    $_.ConfigurationName -eq $configurationName `
                        -and $_.ResourceId -eq $resourceId
                }

                $resourceCurrentState.DomainName | Should -Be $ConfigurationData.AllNodes.DomainName
                $resourceCurrentState.SiteName | Should -Be $ConfigurationData.AllNodes.SiteName
                $resourceCurrentState.Credential | Should -BeNullOrEmpty
                $resourceCurrentState.WaitTimeout | Should -Be 300
                $resourceCurrentState.RestartCount | Should -Be 0
                $resourceCurrentState.IsAvailable | Should -BeTrue
            }

            It 'Should return $true when Test-DscConfiguration is run' {
                Test-DscConfiguration -Verbose | Should -Be 'True'
            }
        }

        $configurationName = "$($script:dscResourceName)_WaitDomainControllerUsingCredential_Config"

        Context ('When using configuration {0}' -f $configurationName) {
            It 'Should compile and apply the MOF without throwing' {
                {
                    $configurationParameters = @{
                        OutputPath        = $TestDrive
                        # The variable $ConfigurationData was dot-sourced above.
                        ConfigurationData = $ConfigurationData
                    }

                    & $configurationName @configurationParameters

                    $startDscConfigurationParameters = @{
                        Path         = $TestDrive
                        ComputerName = 'localhost'
                        Wait         = $true
                        Verbose      = $true
                        Force        = $true
                        ErrorAction  = 'Stop'
                    }

                    Start-DscConfiguration @startDscConfigurationParameters
                } | Should -Not -Throw
            }

            It 'Should be able to call Get-DscConfiguration without throwing' {
                {
                    $script:currentConfiguration = Get-DscConfiguration -Verbose -ErrorAction Stop
                } | Should -Not -Throw
            }

            It 'Should have set the resource and all the parameters should match' {
                $resourceCurrentState = $script:currentConfiguration | Where-Object -FilterScript {
                    $_.ConfigurationName -eq $configurationName `
                        -and $_.ResourceId -eq $resourceId
                }

                $resourceCurrentState.DomainName | Should -Be $ConfigurationData.AllNodes.DomainName
                $resourceCurrentState.SiteName | Should -Be $ConfigurationData.AllNodes.SiteName
                $resourceCurrentState.Credential.UserName | Should -Be $ConfigurationData.AllNodes.AdministratorUserName
                $resourceCurrentState.WaitTimeout | Should -Be 300
                $resourceCurrentState.RestartCount | Should -Be 0
                $resourceCurrentState.IsAvailable | Should -BeTrue
            }

            It 'Should return $true when Test-DscConfiguration is run' {
                Test-DscConfiguration -Verbose | Should -Be 'True'
            }
        }

        $configurationName = "$($script:dscResourceName)_WaitDomainControllerUsingPsDscRunAsCredential_Config"

        Context ('When using configuration {0}' -f $configurationName) {
            It 'Should compile and apply the MOF without throwing' {
                {
                    $configurationParameters = @{
                        OutputPath        = $TestDrive
                        # The variable $ConfigurationData was dot-sourced above.
                        ConfigurationData = $ConfigurationData
                    }

                    & $configurationName @configurationParameters

                    $startDscConfigurationParameters = @{
                        Path         = $TestDrive
                        ComputerName = 'localhost'
                        Wait         = $true
                        Verbose      = $true
                        Force        = $true
                        ErrorAction  = 'Stop'
                    }

                    Start-DscConfiguration @startDscConfigurationParameters
                } | Should -Not -Throw
            }

            It 'Should be able to call Get-DscConfiguration without throwing' {
                {
                    $script:currentConfiguration = Get-DscConfiguration -Verbose -ErrorAction Stop
                } | Should -Not -Throw
            }

            It 'Should have set the resource and all the parameters should match' {
                $resourceCurrentState = $script:currentConfiguration | Where-Object -FilterScript {
                    $_.ConfigurationName -eq $configurationName `
                        -and $_.ResourceId -eq $resourceId
                }

                $resourceCurrentState.DomainName | Should -Be $ConfigurationData.AllNodes.DomainName
                $resourceCurrentState.SiteName | Should -Be $ConfigurationData.AllNodes.SiteName
                $resourceCurrentState.Credential | Should -BeNullOrEmpty
                $resourceCurrentState.WaitTimeout | Should -Be 300
                $resourceCurrentState.RestartCount | Should -Be 0
                $resourceCurrentState.IsAvailable | Should -BeTrue
            }

            It 'Should return $true when Test-DscConfiguration is run' {
                Test-DscConfiguration -Verbose | Should -Be 'True'
            }
        }

        $configurationName = "$($script:dscResourceName)_WaitDomainControllerInSite_Config"

        Context ('When using configuration {0}' -f $configurationName) {
            It 'Should compile and apply the MOF without throwing' {
                {
                    $configurationParameters = @{
                        OutputPath        = $TestDrive
                        # The variable $ConfigurationData was dot-sourced above.
                        ConfigurationData = $ConfigurationData
                    }

                    & $configurationName @configurationParameters

                    $startDscConfigurationParameters = @{
                        Path         = $TestDrive
                        ComputerName = 'localhost'
                        Wait         = $true
                        Verbose      = $true
                        Force        = $true
                        ErrorAction  = 'Stop'
                    }

                    Start-DscConfiguration @startDscConfigurationParameters
                } | Should -Not -Throw
            }

            It 'Should be able to call Get-DscConfiguration without throwing' {
                {
                    $script:currentConfiguration = Get-DscConfiguration -Verbose -ErrorAction Stop
                } | Should -Not -Throw
            }

            It 'Should have set the resource and all the parameters should match' {
                $resourceCurrentState = $script:currentConfiguration | Where-Object -FilterScript {
                    $_.ConfigurationName -eq $configurationName `
                        -and $_.ResourceId -eq $resourceId
                }

                $resourceCurrentState.DomainName | Should -Be $ConfigurationData.AllNodes.DomainName
                $resourceCurrentState.SiteName | Should -Be $ConfigurationData.AllNodes.SiteName
                $resourceCurrentState.Credential | Should -BeNullOrEmpty
                $resourceCurrentState.WaitTimeout | Should -Be 300
                $resourceCurrentState.RestartCount | Should -Be 0
                $resourceCurrentState.IsAvailable | Should -BeTrue
            }

            It 'Should return $true when Test-DscConfiguration is run' {
                Test-DscConfiguration -Verbose | Should -Be 'True'
            }
        }

        $configurationName = "$($script:dscResourceName)_FailedWaitDomainController_Config"

        Context ('When using configuration {0}' -f $configurationName) {
            It 'Should compile and apply the MOF without throwing' {
                {
                    $configurationParameters = @{
                        OutputPath        = $TestDrive
                        # The variable $ConfigurationData was dot-sourced above.
                        ConfigurationData = $ConfigurationData
                    }

                    & $configurationName @configurationParameters

                    $startDscConfigurationParameters = @{
                        Path         = $TestDrive
                        ComputerName = 'localhost'
                        Wait         = $true
                        Verbose      = $true
                        Force        = $true
                        ErrorAction  = 'Stop'
                    }

                    Start-DscConfiguration @startDscConfigurationParameters
                } | Should -Throw 'No domain controller was found. (WFADD0010)'
            }

            It 'Should be able to call Get-DscConfiguration without throwing' {
                {
                    $script:currentConfiguration = Get-DscConfiguration -Verbose -ErrorAction Stop
                } | Should -Not -Throw
            }

            It 'Should have set the resource and all the parameters should match' {
                $resourceCurrentState = $script:currentConfiguration | Where-Object -FilterScript {
                    $_.ConfigurationName -eq $configurationName `
                        -and $_.ResourceId -eq $resourceId
                }

                $resourceCurrentState.DomainName | Should -Be 'unknown.local'
                $resourceCurrentState.SiteName | Should -BeNullOrEmpty
                $resourceCurrentState.Credential | Should -BeNullOrEmpty
                $resourceCurrentState.WaitTimeout | Should -Be 3
                $resourceCurrentState.RestartCount | Should -Be 0
                $resourceCurrentState.IsAvailable | Should -BeFalse
            }

            It 'Should return $false when Test-DscConfiguration is run' {
                Test-DscConfiguration -Verbose | Should -Be 'False'
            }
        }

        $configurationName = "$($script:dscResourceName)_FailedWaitDomainControllerInSite_Config"

        Context ('When using configuration {0}' -f $configurationName) {
            It 'Should compile and apply the MOF without throwing' {
                {
                    $configurationParameters = @{
                        OutputPath        = $TestDrive
                        # The variable $ConfigurationData was dot-sourced above.
                        ConfigurationData = $ConfigurationData
                    }

                    & $configurationName @configurationParameters

                    $startDscConfigurationParameters = @{
                        Path         = $TestDrive
                        ComputerName = 'localhost'
                        Wait         = $true
                        Verbose      = $true
                        Force        = $true
                        ErrorAction  = 'Stop'
                    }

                    Start-DscConfiguration @startDscConfigurationParameters
                } | Should -Throw 'No domain controller was found. (WFADD0010)'
            }

            It 'Should be able to call Get-DscConfiguration without throwing' {
                {
                    $script:currentConfiguration = Get-DscConfiguration -Verbose -ErrorAction Stop
                } | Should -Not -Throw
            }

            It 'Should have set the resource and all the parameters should match' {
                $resourceCurrentState = $script:currentConfiguration | Where-Object -FilterScript {
                    $_.ConfigurationName -eq $configurationName `
                        -and $_.ResourceId -eq $resourceId
                }

                $resourceCurrentState.DomainName | Should -Be 'unknown.local'
                $resourceCurrentState.SiteName | Should -BeNullOrEmpty
                $resourceCurrentState.Credential | Should -BeNullOrEmpty
                $resourceCurrentState.WaitTimeout | Should -Be 3
                $resourceCurrentState.RestartCount | Should -Be 0
                $resourceCurrentState.IsAvailable | Should -BeFalse
            }

            It 'Should return $false when Test-DscConfiguration is run' {
                Test-DscConfiguration -Verbose | Should -Be 'False'
            }
        }
    }
}
finally
{
    #region FOOTER
    Restore-TestEnvironment -TestEnvironment $script:testEnvironment
    #endregion
}


text:
All notable changes to this project will be documented in this file.
See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines.

## [1.0.1](https://github.com/micro-analytics/micro-analytics/compare/micro-analytics-adapter-utils@1.0.0...micro-analytics-adapter-utils@1.0.1) (2017-06-25)

### Bug Fixes

* Fix typo in adapter utils files list ([06bd853](https://github.com/micro-analytics/micro-analytics/commit/06bd853))


text:
package net.shrimpworks.subvision;

import java.io.File;
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.List;

import javax.xml.parsers.ParserConfigurationException;

import net.shrimpworks.subvision.entities.Author;
import net.shrimpworks.subvision.entities.LogEntry;
import org.xml.sax.SAXException;

import org.junit.Test;

import static org.junit.Assert.*;

public class LogParserTest {

	@Test
	public void testLoadXmlFile() throws URISyntaxException, IOException, SAXException, ParserConfigurationException {
		List<LogEntry> entries = new LogParser(new File(this.getClass().getResource("test.xml").toURI())).entries();
		assertFalse(entries.isEmpty());

		LogEntry entry;

		// verify first log entry against known values
		entry = entries.get(0);
		assertEquals(new Author("bob"), entry.author());
		assertEquals(45756, entry.revision());
		assertFalse(entry.paths().isEmpty());
		assertEquals("Running log message", entry.message());

		// verify oldest log entry against known values
		entry = entries.get(entries.size() - 1);
		assertEquals(new Author("tommy"), entry.author());
		assertEquals(45714, entry.revision());
		assertFalse(entry.paths().isEmpty());
		assertEquals("Rather log message", entry.message());
	}
}


text:
import {
	combineReducers
} from 'redux-immutable';

import Counters from './Counters';
import Messaging from './Messaging';
import DummyReducer from 'common/state/DummyReducer';

export default {
	App: combineReducers({
		Counters: Counters,
		Messaging: Messaging,
		windows : DummyReducer,
	})
};


text:
<!DOCTYPE HTML>

    <title>Simple i-form</title>


text:
module Ptolemy

  class BaseMap
    attr_reader :opts, :path_translator

    def initialize_copy(other)
      @opts = {}
      other.opts.each do |key, value|
        @opts[key] = value.dup
      end
      @path_translator = other.path_translator.dup
    end

    def map_from(output, source_value)
      if map_condition?
          map_output(output, source_value) if map_condition.is_satisfied_by(source_value)
      else
          map_output(output, source_value)
      end
    end

    def register_condition(condition_key, condition, &block)
      map_condition.register(condition_key, condition, &block)
    end

    def register_customized(&block)
      @customized_map = block
    end

    protected

    def map_condition
      @map_condition ||= MapCondition.new
    end

    def map_condition?
      @map_condition
    end

  end

end


text:
<?php

namespace ischenko\yii2\jsloader\base;

use ischenko\yii2\jsloader\ConfigInterface;
use ischenko\yii2\jsloader\filters\Chain as ChainFilter;
use ischenko\yii2\jsloader\filters\ClassName as ClassNameFilter;
use ischenko\yii2\jsloader\filters\NotEmptyFiles as NotEmptyFilesFilter;
use ischenko\yii2\jsloader\filters\Position as PositionFilter;
use ischenko\yii2\jsloader\helpers\JsExpression;
use ischenko\yii2\jsloader\LoaderInterface;
use ischenko\yii2\jsloader\ModuleInterface;
use Yii;
use yii\base\BaseObject;
use yii\base\InvalidConfigException;
use yii\helpers\FileHelper;
use yii\web\AssetBundle;
use yii\web\View;

/**
 * Base class for JS loaders
 *
 * @author Roman Ishchenko <roman@ishchenko.ck.ua>
 * @since 1.0
 */
abstract class Loader extends BaseObject implements LoaderInterface
{
    /**
     * @var string
     */
    public $runtimePath = '@runtime/jsloader';

    /**
     * @var View
     */
    private $view;

    /**
     * @var ClassNameFilter
     */
    private $ignoredBundles;

    /**
     * @var PositionFilter
     */
    private $ignoredPositions;

    /**
     * @var array
     */
    private $seenAssetBundles = [];

    /**
     * Loader constructor.
     *
     * @param View $view
     * @param array $config
     */
    public function __construct(View $view, array $config = [])
    {
        $this->view = $view;
        $this->setIgnoreBundles([]);
        $this->setIgnorePositions([View::POS_HEAD]);

        parent::__construct($config);
    }

    /**
     * @return \ischenko\yii2\jsloader\ConfigInterface an object that implements configuration interface
     */
    abstract public function getConfig(): ConfigInterface;

    /**
     * @return \yii\web\View the view object associated with the loader
     */
    public function getView()
    {
        return $this->view;
    }

    /**
     * @param array $bundles a list of asset bundles names which should be ignored by the loader
     */
    public function setIgnoreBundles(array $bundles)
    {
        $this->ignoredBundles = new ClassNameFilter($bundles);
    }

    /**
     * @param array $positions a list of positions which should be skipped by the loader
     */
    public function setIgnorePositions(array $positions)
    {
        $this->ignoredPositions = new PositionFilter($positions);
    }

    /**
     * Sets new configuration for the loader
     *
     * @param ConfigInterface|array $config
     * @return $this
     */
    public function setConfig($config): LoaderInterface
    {
        $configObject = $this->getConfig();

        if (is_object($config)) {
            $config = get_object_vars($config);
        }

        foreach ((array)$config as $key => $value) {
            $configObject->$key = $value;
        }

        $this->seenAssetBundles = [];

        return $this;
    }

    /**
     * Performs processing of assets registered in the view
     *
     * @return void
     */
    public function processAssets(): void
    {
        $expressions = [];

        foreach ([
                     View::POS_HEAD,
                     View::POS_BEGIN,
                     View::POS_END,
                     View::POS_LOAD,
                     View::POS_READY
                 ] as $position
        ) {
            if ($this->ignoredPositions->match($position)) {
                continue;
            }

            if (($jsExpression = $this->createJsExpression($position)) === null) {
                continue;
            }

            $expressions[$position] = $jsExpression;
        }

        $this->renderJs($expressions);
    }

    /**
     * Start processing asset bundles with further publish
     * @since 1.3
     */
    public function processBundles(): void
    {
        $view = $this->getView();

        foreach (array_keys($view->assetBundles) as $name) {
            $this->registerAssetBundle($name);
        }
    }

    /**
     * Adds a new JS expressions to loader
     *
     * @param array $expressions
     *
     * @return void
     */
    abstract protected function renderJs(array $expressions): void;

    /**
     * Registers asset bundle in the loader
     *
     * @param string $name
     *
     * @return ModuleInterface|false an instance of registered module or false if asset bundle was not registered
     */
    protected function registerAssetBundle(string $name)
    {
        if (($bundle = $this->getAssetBundleFromView($name)) === false) {
            return $bundle;
        }

        $config = $this->getConfig();

        if (!($module = $config->getModule($name))) {
            $module = $config->addModule($name);
        } elseif (isset($this->seenAssetBundles[$name])) {
            return $module;
        }

        $this->seenAssetBundles[$name] = true;

        $options = ['baseUrl' => $bundle->baseUrl];

        $options += $bundle->jsOptions ?: [];
        $options += ['position' => View::POS_END];

        $module->setOptions($options);

        foreach ($bundle->depends as $dependency) {
            if (($dependency = $this->registerAssetBundle($dependency)) !== false) {
                $module->addDependency($dependency);
            }
        }

        $this->importJsFilesFromBundle($bundle, $module);

        return $module;
    }

    /**
     * @return string a path to runtime folder
     */
    protected function getRuntimePath()
    {
        static $runtimePath = [];

        if (!isset($runtimePath[$this->runtimePath])) {
            $rtPath = Yii::getAlias($this->runtimePath);

            if (!FileHelper::createDirectory($rtPath)) {
                throw new InvalidConfigException('Cannot create runtime folder "' . $rtPath . '"');
            }

            $runtimePath[$this->runtimePath] = $rtPath;
        }

        return $runtimePath[$this->runtimePath];
    }

    /**
     * @param integer $position
     *
     * @return JsExpression
     */
    private function createJsExpression($position)
    {
        $chainFilter = new ChainFilter(
            [
                new PositionFilter($position),
                new NotEmptyFilesFilter()
            ]
            , ChainFilter::LOGICAL_AND
        );

        $modules = $this->getConfig()->getModules($chainFilter);
        $code = $this->importJsCodeFromView($position);
        $depends = $this->importJsFilesFromView($position);

        $jsExpression = null;

        if (!empty($code) || !empty($depends)) {
            $jsExpression = new JsExpression($code, $depends);
        }

        if ($modules !== []) {
            $jsExpression = new JsExpression($jsExpression, $modules);
        }

        return $jsExpression;
    }

    /**
     * @param integer $position
     *
     * @return array
     */
    private function importJsFilesFromView($position)
    {
        $modules = [];
        $view = $this->getView();
        $config = $this->getConfig();

        if (!empty($view->jsFiles[$position])) {
            foreach ($view->jsFiles[$position] as $jsFile) {
                if (preg_match('/src=(["\\\'])(.*?)\1/', $jsFile, $matches)) {
                    $modules[] = $config->addModule(md5($matches[2]))
                        ->addFile($matches[2], ['position' => $position]);
                }
            }

            unset($view->jsFiles[$position]);
        }

        return $modules;
    }

    /**
     * @param integer $position
     *
     * @return string
     */
    private function importJsCodeFromView($position)
    {
        $code = '';
        $view = $this->getView();

        if (!empty($view->js[$position])) {
            $code = implode("\n", $view->js[$position]);
            unset($view->js[$position]);
        }

        return $code;
    }

    /**
     * @param string $name
     *
     * @return AssetBundle|false an asset bundle from the view or false if asset bundle not found
     */
    private function getAssetBundleFromView($name)
    {
        $view = $this->getView();

        if (!isset($view->assetBundles[$name])) {
            return false;
        }

        $bundle = $view->assetBundles[$name];

        if (!($bundle instanceof AssetBundle)) {
            return false;
        }

        if ($this->ignoredBundles->match($name)
            || $this->ignoredPositions->match($bundle->jsOptions)
        ) {
            return false;
        }

        return $bundle;
    }

    /**
     * @param AssetBundle $bundle
     * @param ModuleInterface $module
     */
    private function importJsFilesFromBundle(AssetBundle $bundle, ModuleInterface $module)
    {
        $ignoredJs = [];
        $assetManager = $this->getView()->getAssetManager();

        foreach ($bundle->js as $js) {
            $file = $js;
            $options = [];

            if (is_array($js)) {
                if ($this->ignoredPositions->match($js)) {
                    $ignoredJs[] = $js;
                    continue;
                }

                $file = array_shift($js);
                $options = $js;
            }

            $module->addFile($assetManager->getAssetUrl($bundle, $file), $options);
        }

        $bundle->js = $ignoredJs;
    }
}