text:
namespace pwgfemto {

/// Cut on the sum of the PT
template <typename T1, typename T2>
struct AddPairCutV0Attr : public T1, public T2 {

  bool Pass(const AliFemtoV0 &v0_1, const AliFemtoV0 &v0_2)
    {
      return T1::Pass(v0_1, v0_2) && T2::Pass(v0_1, v0_2);
    }

  void FillConfiguration(AliFemtoConfigObject &cfg) const
    {
      T1::FillConfiguration(cfg);
      T2::FillConfiguration(cfg);
    }

  virtual ~AddPairCutV0Attr() {}
};

/// Cut on the sum of the PT
///
struct PairCutV0AttrPt {

  std::pair<double, double> pt_range;

  bool Pass(const AliFemtoV0 &trk1, const AliFemtoV0 &trk2)
    {
      const double pt_sum = trk1.PtV0() + trk2.PtV0();
      return pt_range.first <= pt_sum && pt_sum < pt_range.second;
    }

  void FillConfiguration(AliFemtoConfigObject &cfg) const
    {
      cfg.insert("pt_range", pt_range);
    }

  virtual ~PairCutV0AttrPt() {}
};

/// Simple cut removing pairs sharing a daugther track
struct PairCutV0SharedDaughters {

  bool Pass(const AliFemtoV0 &trk1, const AliFemtoV0 &trk2)
    {
      return trk1.IdNeg() != trk2.IdNeg()
          && trk1.IdPos() != trk2.IdPos();
    }

  void FillConfiguration(AliFemtoConfigObject &) const
    { }

  virtual ~PairCutV0SharedDaughters() {}
};

/// \class PairCutV0MinEntranceSep
/// \brief Accept pairs where TPC entrance separation is larger than
///        some parameter
///
struct PairCutV0MinEntranceSep {

  double min_entrance_sep;

  bool Pass(const AliFemtoV0 &trk1, const AliFemtoV0 &trk2)
    {
      const auto
        dpos = trk1.NominalTpcEntrancePointPos() - trk2.NominalTpcEntrancePointPos(),
        dneg = trk1.NominalTpcEntrancePointNeg() - trk2.NominalTpcEntrancePointNeg();

      const double
        min_sep_sqrd = min_entrance_sep * min_entrance_sep;

       return min_sep_sqrd <= dpos.Mag2()
           && min_sep_sqrd <= dneg.Mag2();
    }

  void FillConfiguration(AliFemtoConfigObject &cfg) const
    {
      cfg.insert("min_entrance_sep", min_entrance_sep);
    }

  virtual ~PairCutV0MinEntranceSep() {}
};

/// \class PairCutV0AvgSep
/// \brief Cut pairs with child-tracks likely split track
///
struct PairCutV0AvgSep {

  double min_avgsep_nn,
         min_avgsep_np,
         min_avgsep_pn,
         min_avgsep_pp;

  PairCutV0AvgSep()
    : min_avgsep_nn(0)
    , min_avgsep_np(0)
    , min_avgsep_pn(0)
    , min_avgsep_pp(0)
    {
    }

  bool Pass(const AliFemtoV0 &trk1, const AliFemtoV0 &trk2)
    {
      double avgsep_nn = -1.0,
             avgsep_np = -1.0,
             avgsep_pn = -1.0,
             avgsep_pp = -1.0;

      AliFemtoPair::CalcAvgSepV0V0(*trk1, *trk2,
                                   avgsep_nn,
                                   avgsep_np,
                                   avgsep_pn,
                                   avgsep_pp);

      return min_avgsep_nn <= avgsep_nn
          && min_avgsep_np <= avgsep_np
          && min_avgsep_pn <= avgsep_pn
          && min_avgsep_pp <= avgsep_pp;
    }

  void FillConfiguration(AliFemtoConfigObject &cfg) const
    {
      cfg.insert("min_avgsep_nn", min_avgsep_nn);
      cfg.insert("min_avgsep_np", min_avgsep_np);
      cfg.insert("min_avgsep_pn", min_avgsep_pn);
      cfg.insert("min_avgsep_pp", min_avgsep_pp);
    }

  static bool is_unset_vector(const AliFemtoThreeVector& v)
    {
      return v.x() <= -9999.0
          || v.y() <= -9999.0
          || v.z() <= -9999.0;
    }

  virtual ~PairCutV0AvgSep() {}
};

}  // namespace

#endif


text:
' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.

Imports System.Collections.Generic
Imports Microsoft.CodeAnalysis.OrderModifiers

Namespace Microsoft.CodeAnalysis.VisualBasic.OrderModifiers
    Friend Class VisualBasicOrderModifiersHelper
        Inherits AbstractOrderModifiersHelpers

        Public Shared ReadOnly Instance As New VisualBasicOrderModifiersHelper()

        Private Sub New()
        End Sub

        Protected Overrides Function GetKeywordKind(trimmed As String) As Integer
            Dim kind = SyntaxFacts.GetKeywordKind(trimmed)
            Return If(kind = SyntaxKind.None, SyntaxFacts.GetContextualKeywordKind(trimmed), kind)
        End Function

        'Protected Overrides Function TryParse(String value, out Dictionary<int, int> parsed) As Boolean
        '{
        '    If (!base.TryParse(value, out parsed))
        '    {
        '        Return False;
        '    }

        '    // 'partial' must always go at the end in C#.
        '    parsed[(int)SyntaxKind.PartialKeyword] = int.MaxValue;
        '    Return True;
        '}
    End Class
End Namespace

redpajama_set_name: RedPajamaGithub


text:
<?php

class String_helper_test extends CI_TestCase {

	public function set_up()
	{
		$this->helper('string');
	}

	public function test_strip_slashes()
	{
		$expected = array(
			"Is your name O'reilly?",
			"No, my name is O'connor."
		);

		$str = array(
			"Is your name O\'reilly?",
			"No, my name is O\'connor."
		);

		$this->assertEquals($expected, strip_slashes($str));
	}

	// --------------------------------------------------------------------

	public function test_strip_quotes()
	{
		$strs = array(
			'"me oh my!"'		=> 'me oh my!',
			"it's a winner!"	=> 'its a winner!',
		);

		foreach ($strs as $str => $expect)
		{
			$this->assertEquals($expect, strip_quotes($str));
		}
	}

	// --------------------------------------------------------------------

	public function test_quotes_to_entities()
	{
		$strs = array(
			'"me oh my!"'		=> '"me oh my!"',
			"it's a winner!"	=> 'it's a winner!',
		);

		foreach ($strs as $str => $expect)
		{
			$this->assertEquals($expect, quotes_to_entities($str));
		}
	}

	// --------------------------------------------------------------------

	public function test_reduce_double_slashes()
	{
		$strs = array(
			'http://codeigniter.com'		=> 'http://codeigniter.com',
			'//var/www/html/example.com/'	=> '/var/www/html/example.com/',
			'/var/www/html//index.php'		=> '/var/www/html/index.php'
		);

		foreach ($strs as $str => $expect)
		{
			$this->assertEquals($expect, reduce_double_slashes($str));
		}
	}

	// --------------------------------------------------------------------

	public function test_reduce_multiples()
	{
		$strs = array(
			'Fred, Bill,, Joe, Jimmy'	=> 'Fred, Bill, Joe, Jimmy',
			'Ringo, John, Paul,,'		=> 'Ringo, John, Paul,'
		);

		foreach ($strs as $str => $expect)
		{
			$this->assertEquals($expect, reduce_multiples($str));
		}

		$strs = array(
			'Fred, Bill,, Joe, Jimmy'	=> 'Fred, Bill, Joe, Jimmy',
			'Ringo, John, Paul,,'		=> 'Ringo, John, Paul'
		);

		foreach ($strs as $str => $expect)
		{
			$this->assertEquals($expect, reduce_multiples($str, ',', TRUE));
		}
	}

	// --------------------------------------------------------------------

	public function test_random_string()
	{
		$this->assertEquals(16, strlen(random_string('alnum', 16)));
		$this->assertEquals(32, strlen(random_string('unique', 16)));
		$this->assertInternalType('string', random_string('numeric', 16));
	}

	// --------------------------------------------------------------------

	public function test_increment_string()
	{
		$this->assertEquals('my-test_1', increment_string('my-test'));
		$this->assertEquals('my-test-1', increment_string('my-test', '-'));
		$this->assertEquals('file_5', increment_string('file_4'));
		$this->assertEquals('file-5', increment_string('file-4', '-'));
		$this->assertEquals('file-5', increment_string('file-4', '-'));
		$this->assertEquals('file-1', increment_string('file', '-', '1'));
		$this->assertEquals(124, increment_string('123', ''));
	}

}


text:
module Polyseerio
  module Agent
    # Introduce metric handlers.
    module Handler
      def self.metric
        {
          Metric::MEMORY => proc do |_config, client|
            client.instance.add_gauge 'memory', 0
          end,

          Metric::CPU => proc do |_config, client|
            client.instance.add_gauge 'cpu_user', 0
            client.instance.add_gauge 'cpu_system', 0
          end,

          Metric::UPTIME => proc do |_config, client|
            client.instance.add_gauge 'uptime', 0
          end
        }
      end
    end
  end
end


text:
layout: post
title: iOS私有API之wifi扫描和wifi连接
description: ""
category: 客户端开发
tags: [iOS,私有AP,wifi扫描,wifi连接]
keywords: iOS,私有AP,wifi扫描,wifi连接
---

公开的api

如果只是想获取已连接的wifi信息。apple已经有公开的api可以使用.

首先需要

```objc
#import <SystemConfiguration/CaptiveNetwork.h>

+ (id)fetchSSIDInfo
{
NSArray *ifs = (id)CNCopySupportedInterfaces();
NSLog(@"%s: Supported interfaces: %@", __func__, ifs);
id info = nil;
for (NSString *ifnam in ifs) {
info = (id)CNCopyCurrentNetworkInfo((CFStringRef)ifnam);
if (info && [info count]) {
break;
}
[info release];
}
[ifs release];
return [info autorelease];
}
```

私有api
首先需要链接到设备系统的lib包。注意,这里ios4和ios5,6是不一样的。

```
 //iOS5+
libHandle = dlopen("System/Library/SystemConfiguration/IPConfiguration.bundle/IPConfiguration", RTLD_LAZY);
//iOS4
// libHandle = dlopen("/System/Library/SystemConfiguration/WiFiManager.bundle/WiFiManager", RTLD_LAZY);
这里使用的是Apple80211.h。
apple80211Open = dlsym(libHandle, "Apple80211Open");
apple80211Bind = dlsym(libHandle, "Apple80211BindToInterface");
apple80211Close = dlsym(libHandle, "Apple80211Close");
apple80211Scan = dlsym(libHandle, "Apple80211Scan");
apple80211Associate = dlsym(libHandle, "Apple80211Associate");
apple80211Open(&airportHandle);
apple80211Bind(airportHandle, @"en0");
```

扫描wifi的时候最好使用异步

```
- (void)scanNetworks
{
NSLog(@"Scanning WiFi Channels...");
NSDictionary *parameters = [NSDictionary alloc] init];
NSArray *scan_networks; //is a CFArrayRef of CFDictionaryRef(s) containing key/value data on each discovered network
apple80211Scan(airportHandle, &scan_networks, parameters);
// NSLog(@"===--======\n%@",scan_networks);
networks = [NSMutableDictionary alloc] init];
networkDicts = [NSMutableArray array];
for (int i = 0; i < [scan_networks count]; i++) {
[networks setObject:[scan_networks objectAtIndex: i] forKey:[scan_networks objectAtIndex: i] objectForKey:@"BSSID"];
[networkDicts addObject:[scan_networks objectAtIndex: i];
}
NSLog(@"Scanning WiFi Channels Finished.");
}

```

连接某个wifi,注意,如果没密码可以传null,返回值如果为0则说明成功

```
- (int)associateToNetwork:(NSString *)SSID withPassword:(NSString *)password
{
for (id key in networks) {
if ([[networks objectForKey:key] objectForKey:@"SSID_STR"] isEqualToString:SSID]) {
// For connecting to WPA network, replace NULL below with a string containing the key
// apple80211Associate;
int associateResult = apple80211Associate(airportHandle, [networks objectForKey:key],password);
// int associateResult = 1;
return associateResult;
}
}
return -1;
}
```

打包和调试部分:

调用私有api需要比普通app更高级的权限。一般安装的app是会在程序(用户)这个文件夹里。而我们的app必须要放在程序(系统)下。

网上讲了很多把app上传到设备的程序(系统)的文件夹,下面我说下我的做法

打开xcode – Product – Build For -Archiving

在设备上(iPhone或iPad),打开Cydia,在首页 – 用户指南 – OpenSSH Access How-To 安装OpenSSH(注意默认密码是alpine)

然后打开itools-高级功能 – 打开ssh

在命令行通过shh把生成好的app上传到设备的程序(系统)文件夹下
```
scp -P 5000 -r /Users/carlosk/Library/Developer/Xcode/DerivedData/WifiPlus_workspace-aokocyaishpniuhfkvpcpzwjvjex/Build/Products/Release-iphoneos/WifiScanPrivateAPI.app root@127.0.0.1:/Applications
/
```

如果是第一次run到设备上,则需要重启,快捷键是按住Home和电源键 5-8秒。以后每次打包到设备上,只需要把app关闭掉,重新打开就可以了。

这种方式的缺点

调用私有api,故无法提交appsotre审核。

调试非常麻烦,没有办法做实时的调试

需要安装在设备的application文件夹下,开发的时候可以使用shh,但是正式发布的时候我现在所知的方法就是一种:采用deb文件。具体我还没看,大家可以百度下。

最后:

这是我第一次对私有api的尝试,可能会有不少问题。希望各位朋友能给点指点,谢谢。

代码我放在github上。需要的同学可以下过来参考下:https://github.com/carlosk/iphone_wifi

原文链接:http://www.carloschen.cn/?p=206


text:
package ru.atott.combiq.web.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class PropertiesHolder {

    @Value("${web.production}")
    private boolean production;

    @Value("${web.production.domain}")
    private String productionDomain;

    public boolean isProduction() {
        return production;
    }

    public String getProductionDomain() {
        return productionDomain;
    }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet" href="../../../../style.css" type="text/css" media="screen">
<link rel="stylesheet" href="../../../../print.css" type="text/css" media="print">
<meta content="GraphicsUtil,com.yahoo.astra.utils.GraphicsUtil,drawDashedLine" name="keywords">
<title>com.yahoo.astra.utils.GraphicsUtil</title>

YUI Flash Component Documentation	All Packages | All Classes | Index | FramesNo Frames

Class GraphicsUtil	Methods

Package	com.yahoo.astra.utils

Class	public class GraphicsUtil

  Utility functions for drawing to Graphics objects.

See also

flash.display.Graphics

Public Methods

 	Method	Defined by

drawDashedLine(target:Graphics, xStart:Number, yStart:Number, xEnd:Number, yEnd:Number, dashSize:Number = 10, gapSize:Number = 10):void

[static]
   Draws a dashed line between two points.

	GraphicsUtil

Method detail

drawDashedLine	()	method

public static function drawDashedLine(target:Graphics, xStart:Number, yStart:Number, xEnd:Number, yEnd:Number, dashSize:Number = 10, gapSize:Number = 10):void

   Draws a dashed line between two points.

Parameters

	target:Graphics — The x position of the start of the line

	xStart:Number — The y position of the start of the line

	yStart:Number —  The x position of the end of the line

	xEnd:Number —  The y position of the end of the line

	yEnd:Number — the size of dashes, in pixels

	dashSize:Number (default = 10) — the size of gaps between dashes, in pixels

	gapSize:Number (default = 10)


text:
var stripe = require("stripe")("sk_test_J9KoKBvf1HZRzAUIq6gicW3K");

// (Assuming you're using express - expressjs.com)
// Get the credit card details submitted by the form
var stripeToken = request.body.stripeToken;

var charge = stripe.charges.create({
  amount: 1000, // amount in cents, again
  currency: "usd",
  source: stripeToken,
  description: "Example charge"
}, function(err, charge) {
  if (err && err.type === 'StripeCardError') {
    // The card has been declined
  }
});


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
    <meta http-equiv="X-UA-Compatible" content="IE=9"/>
    <meta name="generator" content="Doxygen 1.8.6"/>
    <meta name="viewport" content="width=device-width, initial-scale=1"/>
    <title>Generic Image Library: Models</title>
    <link href="tabs.css" rel="stylesheet" type="text/css"/>

    <link href="doxygen.css" rel="stylesheet" type="text/css" />
    <link href="doxygen-boost.css" rel="stylesheet" type="text/css"/>

Main Page

Modules

Classes

Files

Modules |
Typedefs

Models
Channel

Channel models. Although not required by the ChannelConcept, all GIL-provided channels support arithmetic operations.
More...

Modules

 	scoped_channel_value

 	packed_channel_value

 	packed_channel_reference

 	packed_dynamic_channel_reference

 	Represents a reference proxy to a channel operating over a bit range whose offset is specified at run time. Models ChannelConcept.

Typedefs

using 	float32_t = scoped_channel_value< float, float_point_zero< float >, float_point_one< float >>

 	32-bit floating point channel type with range [0.0f ... 1.0f]. Models ChannelValueConcept

using 	float64_t = scoped_channel_value< double, float_point_zero< double >, float_point_one< double >>

 	64-bit floating point channel type with range [0.0f ... 1.0f]. Models ChannelValueConcept

Detailed Description

Channel models. Although not required by the ChannelConcept, all GIL-provided channels support arithmetic operations.

     <address class="footer">

        Generated on Wed Dec 5 2018 20:05:50 for Generic Image Library by  doxygen 1.8.6

    </address>


text:
<form (submit)="addName()">
  <input [(ngModel)]="newName" name="newName" [attr.placeholder]="'HOME.AWESOME_SCIENTIST_PLACEHOLDER' | translate">
  <button type="submit" translate="BUTTONS.ADD"></button>
</form>

{{ name }}


text:
package org.sindice.rdfcommons.vocabulary;

/**
 * Defines the RDFS vocabulary.
 *
 * @author Michele Mostarda ( mostarda@fbk.eu )
 * @version $Id$
 */
public class RDFSVocabulary extends RDFVocabulary {

    /**
     * Base vocabulary prefix.
     */
    public static final String RDFS_PREFIX = "http://www.w3.org/2000/01/rdf-schema";

    /* ------ BEGIN PROPERTIES ------ */

    /**
     *
rdfs:subClassOf Indicates membership of a class.

     */
    public static final String SUBCLASSOF = RDFS_PREFIX  + "#subClassOf";

    /**
     *
rdfs:subPropertyOf Indicates specialization of properties.

     */
    public static final String SUBPROPERTYOF = RDFS_PREFIX  + "#subPropertyOf";

    /**
     *
rdfs:domain A domain class for a property type.

     */
    public static final String DOMAIN = RDFS_PREFIX  + "#domain";

    /**
     *
rdfs:range A range class for a property type.

     */
    public static final String RANGE = RDFS_PREFIX  + "#range";

    /**
     *
rdfs:label Provides a human-readable version of a resource name.

     */
    public static final String LABEL = RDFS_PREFIX  + "#label";

    /**
     *
rdfs:comment Use this for descriptions.

     */
    public static final String COMMENT = RDFS_PREFIX  + "#comment";

    /**
     *
rdfs:member A member of a container.

     */
    public static final String MEMBER = RDFS_PREFIX  + "#member";

    /**
     *
rdfs:seeAlso A resource that provides information about the subject resource.

     */
    public static final String SEEALSO = RDFS_PREFIX  + "#seeAlso";

    /**
     *
rdfs:isDefinedBy Indicates the namespace of a resource.

     */
    public static final String ISDEFINEDBY = RDFS_PREFIX  + "#isDefinedBy";

    /* ------ END PROPERTIES ------ */

    /* ------ BEGIN CLASSES ------ */

    //rdfs:Resource  	The class resource, everything.
    //rdfs:Literal 	    This represents the set of atomic values, eg. textual strings.
    //rdfs:XMLLiteral 	The class of XML literals.
    //rdfs:Class 	    The concept of Class
    //rdfs:Datatype 	The class of datatypes.
    //rdfs:Container 	This represents the set Containers.
    //rdfs:ContainerMembershipProperty 	The container membership properties, rdfcommons:1, rdfcommons:2, ..., all of which are sub-properties of 'member'.

    /* ------ END CLASSES ------ */

}


text:
(function(ns){

    var Syntax = require('estraverse').Syntax,
        ANNO = require("../../type-system/annotation.js").ANNO,
        Shade = require("../../interfaces.js");

    var UnaryFunctions = {
        "!": function(a) { return !a; },
        "-": function(a) { return -a; },
        "+": function(a) { return +a; },
        "typeof": function(a) { return typeof a; },
        "void": function(a) { return void a; },
        "delete": function(a) { return true; }

    };

    var BinaryFunctions = {
        "+" : function(a,b) { return a + b; },
        "-" : function(a,b) { return a - b; },
        "/" : function(a,b) { return a / b; },
        "*" : function(a,b) { return a * b; },
        "%" : function(a,b) { return a % b; },

        "==" : function(a,b) { return a == b; },
        "!=" : function(a,b) { return a != b; },
        "===" : function(a,b) { return a === b; },
        "!==" : function(a,b) { return a !== b; },
        "<" : function(a,b) { return a < b; },
        "<=" : function(a,b) { return a <= b; },
        ">" : function(a,b) { return a > b; },
        ">=" : function(a,b) { return a >= b; }
    };

    /**
     *
     * @param node
     */
    function getConstantValue(node) {
        if (node.type === Syntax.Literal) {
            var value = node.raw !== undefined ? node.raw : node.value;
            var number = parseFloat(value);
            if (!isNaN(number))
                return number;
            value = node.value;
            switch(value) {
                case "true": return true;
                case "false": return false;
                case "null": return null;
                default: return value;
            }
        }
        if (node.type == Syntax.MemberExpression || node.type == Syntax.CallExpression  || node.type == Syntax.Identifier || node.type == Syntax.NewExpression || node.type == Syntax.LogicalExpression) {
            return ANNO(node).getConstantValue();
        }
        if (node.type === Syntax.UnaryExpression) {
            if (node.operator == "typeof") {
                return ANNO(node).getTypeString();
            }
            if(UnaryFunctions.hasOwnProperty(node.operator)) {
                return UnaryFunctions[node.operator](getConstantValue(node.argument));
            }
            Shade.throwError(node, "Unknown unary operator: " + node.operator);
        }
        if (node.type === Syntax.BinaryExpression) {
            if(BinaryFunctions.hasOwnProperty(node.operator)) {
                return BinaryFunctions[node.operator](getConstantValue(node.left), getConstantValue(node.right));
            }
            Shade.throwError(node, "Unknown binary operator: " + node.operator);
        }
        Shade.throwError(node, "Evaluating static value for node type: " + node.type);
    };

    function getConstantTruthValue(node) {
        var aNode = ANNO(node);

        // !!undefined == false;
        if (aNode.isNullOrUndefined())
            return false;
        // !!{} == true
        if (aNode.isObject() || this.isFunction())
            return true;
        // In all other cases, it depends on the value,
        // thus we can only evaluate this for static objects
        if (aNode.hasConstantValue()) {
            return !!aNode.getConstantValue();
        }
        return undefined;
    }

    exports.getConstantValue = getConstantValue;
    exports.getConstantTruthValue = getConstantTruthValue;

}(exports));


text:
#import "BaseViewController.h"
#import "AppDelegate.h"
#import "RootTabViewController.h"
#import <RDVTabBarController.h>
#import "RootTabViewController.h"

typedef NS_ENUM(NSInteger, AnalyseMethodType) {
    AnalyseMethodTypeJustRefresh = 0,
    AnalyseMethodTypeLazyCreate,
    AnalyseMethodTypeForceCreate
};

@interface BaseViewController ()

@end

@implementation BaseViewController
- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    //[UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleDefault;
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];

}
- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
}

- (void)viewDidLoad{
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
}

- (void)loadView{
    [super loadView];

}

- (void)tabBarItemClicked
{
    //NSLog(@"\ntabBarItemClicked : %@", NSStringFromClass([self class]));
}

+ (UIViewController *)presentingVC{
    UIWindow * window = [[UIApplication sharedApplication] keyWindow];
    if (window.windowLevel != UIWindowLevelNormal)
    {
        NSArray *windows = [[UIApplication sharedApplication] windows];
        for(UIWindow * tmpWin in windows)
        {
            if (tmpWin.windowLevel == UIWindowLevelNormal)
            {
                window = tmpWin;
                break;
            }
        }
    }
    UIViewController *result = window.rootViewController;
    while (result.presentedViewController) {
        result = result.presentedViewController;
    }
    if ([result isKindOfClass:[RootTabViewController class]]) {
        result = [(RootTabViewController *)result selectedViewController];
    }
    if ([result isKindOfClass:[UINavigationController class]]) {
        result = [(UINavigationController *)result topViewController];
    }
    return result;
}

+ (CGSize)sizeToFitWidth  :(CGSize)size newWidth:(CGFloat)newWidth
{
  CGFloat newHeight   = size.height*newWidth/size.width;
  size  = CGSizeMake(newWidth, newHeight);
  return size;
}

+ (CGFloat)heightToFitWidth  :(CGSize)size newWidth:(CGFloat)newWidth
{
  CGFloat newHeight   = size.height*newWidth/size.width;
  return  newHeight;
}

+ (CGFloat)widthToFitHeight  :(CGSize)size newHeight:(CGFloat)newHeight
{
  CGFloat newWidth  = size.width*newHeight/size.height;
  return  newWidth;
}

/**
 *  @author J006, 15-06-03 17:06:20
 *
 *  导航栏push下一个VC
 *
 *  @param vc
 */
+ (void)naviPushViewController:(UIViewController*)vc
{
  assert(vc!=nil);
  UIViewController  *tempVC = [self presentingVC];
  CATransition *animation = [CATransition animation];
  [animation setDuration:kpushViewTime];
  [animation setType:kCATransitionMoveIn];
  [animation setSubtype:kCATransitionFromRight];
  [tempVC.view.window.layer addAnimation:animation forKey:kCATransition];
  [tempVC.navigationController  pushViewController:vc animated:NO];
}

+ (void)naviInsertViewController:(UIViewController*)vc
{
  UIViewController  *tempVC = [self presentingVC];
  [tempVC.navigationController  popViewControllerAnimated:NO];
  CATransition *animation = [CATransition animation];
  [animation setDuration:kpushViewTime];
  [animation setType:kCATransitionMoveIn];
  [animation setSubtype:kCATransitionFromRight];
  [tempVC.view.window.layer addAnimation:animation forKey:kCATransition];
  [tempVC.navigationController  pushViewController:vc animated:NO];
}

+ (void)naviPushViewControllerWithNoAniation:(UIViewController*)vc
{
  assert(vc!=nil);
  UIViewController  *tempVC = [self presentingVC];
  [tempVC.navigationController  pushViewController:vc animated:NO];
}

/**
 *  @author J006, 15-06-03 17:06:43
 *
 *  设置底部导航栏的隐藏和出现
 *
 *  @param isHidden
 *  @param isAnimated
 */
+ (void)setRDVTabHidden:(BOOL)isHidden  isAnimated:(BOOL)isAnimated
{
  UIViewController  *tempVC = [self presentingVC];
  [tempVC.rdv_tabBarController setTabBarHidden:isHidden animated:isAnimated];
}

+ (void)setRDVTabStatusHidden:(BOOL)isHidden
{
  UIViewController  *tempVC = [self presentingVC];
  RootTabViewController *rdv  = (RootTabViewController*)tempVC.rdv_tabBarController;
  [rdv setIsHiddenStatus:isHidden];
  [rdv  setNeedsStatusBarAppearanceUpdate];
  [rdv setIsHiddenStatus:!isHidden];//还原成之前的状态
}

+ (void)setRDVTabStatusHiddenDirect:(BOOL)isHidden
{
  UIViewController  *tempVC = [self presentingVC];
  RootTabViewController *rdv  = (RootTabViewController*)tempVC.rdv_tabBarController;
  [rdv  setNeedsStatusBarAppearanceUpdate];
  [rdv setIsHiddenStatus:isHidden];
}

+ (void)setRDVTabStatusStyle:(UIStatusBarStyle)style  preStyle:(UIStatusBarStyle)preStyle;
{
  UIViewController  *tempVC = [self presentingVC];
  RootTabViewController *rdv  = (RootTabViewController*)tempVC.rdv_tabBarController;
  [rdv setStatusStyle:style];
  [rdv setNeedsStatusBarAppearanceUpdate];
  [rdv setStatusStyle:preStyle];//还原成之前的状态
}

+ (void)setRDVTabStatusStyleDirect:(UIStatusBarStyle)style
{
  UIViewController  *tempVC = [self presentingVC];
  RootTabViewController *rdv  = (RootTabViewController*)tempVC.rdv_tabBarController;
  [rdv setStatusStyle:style];
  [rdv setNeedsStatusBarAppearanceUpdate];
}

+ (BOOL)checkRDVTabIsHidden
{
  BOOL  isHidden  = NO;
  UIViewController  *tempVC = [self presentingVC];
  isHidden  = tempVC.rdv_tabBarController.tabBarHidden;
  return isHidden;
}

/**
 *  @author J006, 15-09-08 17:06:12
 *
 *  设置底部tab栏是否有小红点更新,并设置更新数目
 *
 *  @return
 */
+ (void)setRDVTabAttentionIconHasNewInfo  :(BOOL)hasNewInfo  itemIndex:(NSInteger)index infoNums:(NSInteger)infoNums
{
  UIViewController  *tempVC = [self presentingVC];
  RootTabViewController *rdv  = (RootTabViewController*)tempVC.rdv_tabBarController;
  [rdv setRDVTabItemHasAttentionIconWithItemIndex:index hasAttentionIcon:hasNewInfo attentionNums:infoNums];
}

+ (void)popToTheUIViewController  :(Class)vc
{
  for (UIViewController *temp in [self getNavi].viewControllers) {
    if ([temp isKindOfClass:vc]) {
      [[self getNavi] popToViewController:temp animated:YES];
    }
  }
}

/**
 *  @author J006, 15-06-03 17:06:12
 *
 *  获取导航栏
 *
 *  @return
 */
+ (UINavigationController*)getNavi
{
    UIViewController  *tempVC = [self presentingVC];
    return tempVC.navigationController;
}

+ (void)presentVC:(UIViewController *)viewController{
    UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:viewController];
    viewController.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"关闭" style:UIBarButtonItemStylePlain target:viewController action:@selector(dismissModalViewControllerAnimated:)];
    [[BaseViewController presentingVC] presentViewController:nav animated:YES completion:nil];
}

@end


text:
using asio::ip::tcp;

int main(int argc, char* argv[])
{
  try
  {
    if (argc != 3)
    {
      std::cout << "Usage: sync_client <server> <path>\n";
      std::cout << "Example:\n";
      std::cout << "  sync_client www.boost.org /LICENSE_1_0.txt\n";
      return 1;
    }

    asio::io_context io_context;

    // Get a list of endpoints corresponding to the server name.
    tcp::resolver resolver(io_context);
    tcp::resolver::results_type endpoints = resolver.resolve(argv[1], "http");

    // Try each endpoint until we successfully establish a connection.
    tcp::socket socket(io_context);
    asio::connect(socket, endpoints);

    // Form the request. We specify the "Connection: close" header so that the
    // server will close the socket after transmitting the response. This will
    // allow us to treat all data up until the EOF as the content.
    asio::streambuf request;
    std::ostream request_stream(&request);
    request_stream << "GET " << argv[2] << " HTTP/1.0\r\n";
    request_stream << "Host: " << argv[1] << "\r\n";
    request_stream << "Accept: */*\r\n";
    request_stream << "Connection: close\r\n\r\n";

    // Send the request.
    asio::write(socket, request);

    // Read the response status line. The response streambuf will automatically
    // grow to accommodate the entire line. The growth may be limited by passing
    // a maximum size to the streambuf constructor.
    asio::streambuf response;
    asio::read_until(socket, response, "\r\n");

    // Check that response is OK.
    std::istream response_stream(&response);
    std::string http_version;
    response_stream >> http_version;
    unsigned int status_code;
    response_stream >> status_code;
    std::string status_message;
    std::getline(response_stream, status_message);
    if (!response_stream || http_version.substr(0, 5) != "HTTP/")
    {
      std::cout << "Invalid response\n";
      return 1;
    }
    if (status_code != 200)
    {
      std::cout << "Response returned with status code " << status_code << "\n";
      return 1;
    }

    // Read the response headers, which are terminated by a blank line.
    asio::read_until(socket, response, "\r\n\r\n");

    // Process the response headers.
    std::string header;
    while (std::getline(response_stream, header) && header != "\r")
      std::cout << header << "\n";
    std::cout << "\n";

    // Write whatever content we already have to output.
    if (response.size() > 0)
      std::cout << &response;

    // Read until EOF, writing data to output as we go.
    asio::error_code error;
    while (asio::read(socket, response,
          asio::transfer_at_least(1), error))
      std::cout << &response;
    if (error != asio::error::eof)
      throw asio::system_error(error);
  }
  catch (std::exception& e)
  {
    std::cout << "Exception: " << e.what() << "\n";
  }

  return 0;
}


text:
package db

import java.util.UUID

import io.flow.dependency.v0.models.{Library, Organization, Visibility}
import util.DependencySpec

class LibrariesDaoSpec extends  DependencySpec {

  private[this] lazy val org: Organization = createOrganization()

  private[this] def findAll(
               auth: Authorization = Authorization.All,
               id: Option[String] = None,
               ids: Option[Seq[String]] = None,
               organizationId: Option[String] = None,
               resolverId: Option[String] = None,
               prefix: Option[String] = None,
               limit: Option[Long] = None,
               offset: Long = 0,
             ): Seq[Library] = {
    librariesDao.findAll(
      auth,
      id = id,
      ids = ids,
      organizationId = organizationId,
      resolverId = resolverId,
      prefix = prefix,
      limit = limit,
      offset = offset,
    )
  }

  "findByGroupIdAndArtifactId" in {
    val library = createLibrary(org)
    librariesDao.findByGroupIdAndArtifactId(
      Authorization.All,
      library.groupId,
      library.artifactId
    ).map(_.id) must be(Some(library.id))

    librariesDao.findByGroupIdAndArtifactId(
      Authorization.All,
      library.groupId + "-2",
      library.artifactId
    ) must be (None)

    librariesDao.findByGroupIdAndArtifactId(
      Authorization.All,
      library.groupId,
      library.artifactId + "-2"
    ) must be (None)
  }

  "findById" in {
    val library = createLibrary(org)
    librariesDao.findById(Authorization.All, library.id).map(_.id) must be(
      Some(library.id)
    )

    librariesDao.findById(Authorization.All, UUID.randomUUID.toString) must be(None)
  }

  "findAll by ids" in {
    val library1 = createLibrary(org)
    val library2 = createLibrary(org)

    findAll(ids = Some(Seq(library1.id, library2.id))).map(_.id) must be(
      Seq(library1, library2).sortWith { (x,y) => x.groupId.toString < y.groupId.toString }.map(_.id)
    )

    findAll(ids = Some(Nil)) must be(Nil)
    findAll(ids = Some(Seq(UUID.randomUUID.toString))) must be(Nil)
    findAll(ids = Some(Seq(library1.id, UUID.randomUUID.toString))).map(_.id) must be(Seq(library1.id))
  }

  "findAll by resolver" in {
    val resolver = createResolver(org)
    val form = createLibraryForm(org).copy(resolverId = resolver.id)
    val library = createLibrary(org)(form)

    findAll(resolverId = Some(resolver.id)).map(_.id) must be(Seq(library.id))
  }

  "findAll by prefix" in {
    val org = createOrganization()
    val resolver = createResolver(org)
    val library1 = createLibrary(org)(
      createLibraryForm(org).copy(resolverId = resolver.id, artifactId = "foo-bar")
    )
    val library2 = createLibrary(org)(
      createLibraryForm(org).copy(resolverId = resolver.id, artifactId = "foo-baz")
    )

    def ids(prefix: String) = {
      findAll(
        Authorization.All,
        organizationId = Some(org.id),
        prefix = Some(prefix),
      ).map(_.id).sorted
    }

    ids("foo") must equal(Seq(library1.id, library2.id).sorted)
    ids("foo-bar") must equal(Seq(library1.id))
    ids("foo-baz") must equal(Seq(library2.id))
    ids(createTestId()) must be(Nil)
  }

  "create" must {
    "validates empty group id" in {
      val form = createLibraryForm(org).copy(groupId = "   ")
      librariesDao.validate(form) must be(
        Seq("Group ID cannot be empty")
      )
    }

    "validates empty artifact id" in {
      val form = createLibraryForm(org).copy(artifactId = "   ")
      librariesDao.validate(form) must be(
        Seq("Artifact ID cannot be empty")
      )
    }

    "validates duplicates" in {
      val library = createLibrary(org)
      val form = createLibraryForm(org).copy(
        groupId = library.groupId,
        artifactId = library.artifactId
      )
      librariesDao.validate(form) must be(
        Seq("Library with this group id and artifact id already exists")
      )
    }
  }

  "authorization" must {

    "allow anybody to access a public library" in {
      val user = createUser()
      val org = createOrganization(user = user)
      val resolver = createResolver(org, user) (
        createResolverForm(org).copy(visibility = Visibility.Public)
      )
      val lib = createLibrary(org, user = user)(createLibraryForm(org)(resolver = resolver))

      findAll(Authorization.PublicOnly, id = Some(lib.id)).map(_.id) must be(Seq(lib.id))
      findAll(id = Some(lib.id)).map(_.id) must be(Seq(lib.id))
      findAll(Authorization.Organization(org.id), id = Some(lib.id)).map(_.id) must be(Seq(lib.id))
      findAll(Authorization.Organization(createOrganization().id), id = Some(lib.id)).map(_.id) must be(Seq(lib.id))
      findAll(Authorization.User(user.id), id = Some(lib.id)).map(_.id) must be(Seq(lib.id))
    }

    "allow only users of an org to access a library w/ a private resolver" in {
      val user = createUser()
      val org = createOrganization(user = user)
      val resolver = createResolver(org, user) (
        createResolverForm(org).copy(visibility = Visibility.Private)
      )
      val lib = createLibrary(org, user = user)(createLibraryForm(org)(resolver = resolver))
      lib.resolver.visibility must be(Visibility.Private)

      findAll(Authorization.PublicOnly, id = Some(lib.id))must be(Nil)
      findAll(id = Some(lib.id)).map(_.id) must be(Seq(lib.id))
      findAll(Authorization.Organization(org.id), id = Some(lib.id)).map(_.id) must be(Seq(lib.id))
      findAll(Authorization.Organization(createOrganization().id), id = Some(lib.id))must be(Nil)
      findAll(Authorization.User(user.id), id = Some(lib.id)).map(_.id) must be(Seq(lib.id))
      findAll(Authorization.User(createUser().id), id = Some(lib.id)) must be(Nil)
    }

  }

}


text:
<a href="<?=base_url('/presensi.html');?>" class="widgets">Semua

<a href="<?=base_url('/presensi/hadir.html');?>" class="support">Hadir

<a href="<?=base_url('/presensi/sakit.html')?>" class="elements">Sakit

<a href="<?=base_url('/presensi/ijin.html')?>" class="editor">Ijin

<a href="<?=base_url('/presensi/alpha.html')?>" class="error">Alpha

<a href="<?=base_url('/presensi/cuti.html')?>" class="error">Cuti

    <?php $this->load->view($container); ?>


text:
package plugin

import (
	"encoding/json"
	"fmt"
	"os"
	"os/exec"
	"path/filepath"
	"testing"

	"github.com/docker/cli/e2e/internal/fixtures"
	"github.com/docker/cli/internal/test/environment"
	"github.com/docker/docker/api/types"
	"github.com/pkg/errors"
	"gotest.tools/v3/assert"
	"gotest.tools/v3/fs"
	"gotest.tools/v3/icmd"
	"gotest.tools/v3/skip"
)

const registryPrefix = "registry:5000"

func TestInstallWithContentTrust(t *testing.T) {
	skip.If(t, environment.SkipPluginTests())

	pluginName := fmt.Sprintf("%s/plugin-content-trust", registryPrefix)

	dir := fixtures.SetupConfigFile(t)
	defer dir.Remove()

	pluginDir := preparePluginDir(t)
	defer pluginDir.Remove()

	icmd.RunCommand("docker", "plugin", "create", pluginName, pluginDir.Path()).Assert(t, icmd.Success)
	result := icmd.RunCmd(icmd.Command("docker", "plugin", "push", pluginName),
		fixtures.WithConfig(dir.Path()),
		fixtures.WithTrust,
		fixtures.WithNotary,
		fixtures.WithPassphrase("foo", "bar"),
	)
	result.Assert(t, icmd.Expected{
		Out: "Signing and pushing trust metadata",
	})

	icmd.RunCommand("docker", "plugin", "rm", "-f", pluginName).Assert(t, icmd.Success)

	result = icmd.RunCmd(icmd.Command("docker", "plugin", "install", "--grant-all-permissions", pluginName),
		fixtures.WithConfig(dir.Path()),
		fixtures.WithTrust,
		fixtures.WithNotary,
	)
	result.Assert(t, icmd.Expected{
		Out: fmt.Sprintf("Status: Downloaded newer image for %s@sha", pluginName),
	})
}

func TestInstallWithContentTrustUntrusted(t *testing.T) {
	skip.If(t, environment.SkipPluginTests())

	dir := fixtures.SetupConfigFile(t)
	defer dir.Remove()

	result := icmd.RunCmd(icmd.Command("docker", "plugin", "install", "--grant-all-permissions", "tiborvass/sample-volume-plugin:latest"),
		fixtures.WithConfig(dir.Path()),
		fixtures.WithTrust,
		fixtures.WithNotary,
	)
	result.Assert(t, icmd.Expected{
		ExitCode: 1,
		Err:      "Error: remote trust data does not exist",
	})
}

func preparePluginDir(t *testing.T) *fs.Dir {
	p := &types.PluginConfig{
		Interface: types.PluginConfigInterface{
			Socket: "basic.sock",
			Types:  []types.PluginInterfaceType{{Capability: "docker.dummy/1.0"}},
		},
		Entrypoint: []string{"/basic"},
	}
	configJSON, err := json.Marshal(p)
	assert.NilError(t, err)

	binPath, err := ensureBasicPluginBin()
	assert.NilError(t, err)

	dir := fs.NewDir(t, "plugin_test",
		fs.WithFile("config.json", string(configJSON), fs.WithMode(0644)),
		fs.WithDir("rootfs", fs.WithMode(0755)),
	)
	icmd.RunCommand("/bin/cp", binPath, dir.Join("rootfs", p.Entrypoint[0])).Assert(t, icmd.Success)
	return dir
}

func ensureBasicPluginBin() (string, error) {
	name := "docker-basic-plugin"
	p, err := exec.LookPath(name)
	if err == nil {
		return p, nil
	}

	goBin, err := exec.LookPath("/usr/local/go/bin/go")
	if err != nil {
		return "", err
	}
	installPath := filepath.Join(os.Getenv("GOPATH"), "bin", name)
	cmd := exec.Command(goBin, "build", "-o", installPath, "./basic")
	cmd.Env = append(os.Environ(), "CGO_ENABLED=0")
	if out, err := cmd.CombinedOutput(); err != nil {
		return "", errors.Wrapf(err, "error building basic plugin bin: %s", string(out))
	}
	return installPath, nil
}


text:
namespace MassTransit
{
    using System;
    using System.Collections.Generic;
    using System.Diagnostics;
    using Context;
    using Diagnostics.Introspection;
    using Events;
    using Exceptions;
    using Logging;
    using Magnum;
    using Magnum.Extensions;
    using Magnum.Reflection;
    using Monitoring;
    using Pipeline;
    using Pipeline.Configuration;
    using Stact;
    using Threading;
    using Util;

    /// <summary>
    /// A service bus is used to attach message handlers (services) to endpoints, as well as
    /// communicate with other service bus instances in a distributed application
    /// </summary>
    [DebuggerDisplay("{DebugDisplay}")]
    public class ServiceBus :
        IControlBus
    {
        static readonly ILog _log;

        ConsumerPool _consumerPool;
        int _consumerThreadLimit = Environment.ProcessorCount*4;
        ServiceBusInstancePerformanceCounters _counters;
        volatile bool _disposed;
        UntypedChannel _eventChannel;
        ChannelConnection _performanceCounterConnection;
        int _receiveThreadLimit = 1;
        TimeSpan _receiveTimeout = 3.Seconds();
        IServiceContainer _serviceContainer;
        volatile bool _started;

        static ServiceBus()
        {
            try
            {
                _log = Logger.Get(typeof(ServiceBus));
            }
            catch (Exception ex)
            {
                throw new ConfigurationException("log4net isn't referenced", ex);
            }
        }

        /// <summary>
        /// Creates an instance of the ServiceBus, which implements IServiceBus. This is normally
        /// not called and should be created using the ServiceBusConfigurator to ensure proper defaults
        /// and operation.
        /// </summary>
        public ServiceBus(IEndpoint endpointToListenOn,
            IEndpointCache endpointCache, bool enablePerformanceCounters)
        {
            ReceiveTimeout = TimeSpan.FromSeconds(3);
            Guard.AgainstNull(endpointToListenOn, "endpointToListenOn", "This parameter cannot be null");
            Guard.AgainstNull(endpointCache, "endpointFactory", "This parameter cannot be null");

            Endpoint = endpointToListenOn;
            EndpointCache = endpointCache;

            _eventChannel = new ChannelAdapter();

            _serviceContainer = new ServiceContainer(this);

            OutboundPipeline = new OutboundPipelineConfigurator(this).Pipeline;
            InboundPipeline = InboundPipelineConfigurator.CreateDefault(this);

            ControlBus = this;

            if(enablePerformanceCounters)
                InitializePerformanceCounters();
        }

        public int ConcurrentReceiveThreads
        {
            get { return _receiveThreadLimit; }
            set
            {
                if (_started)
                    throw new ConfigurationException(
                        "The receive thread limit cannot be changed once the bus is in motion. Beep! Beep!");

                _receiveThreadLimit = value;
            }
        }

        public int MaximumConsumerThreads
        {
            get { return _consumerThreadLimit; }
            set
            {
                if (_started)
                    throw new ConfigurationException(
                        "The consumer thread limit cannot be changed once the bus is in motion. Beep! Beep!");

                _consumerThreadLimit = value;
            }
        }

        public TimeSpan ReceiveTimeout
        {
            get { return _receiveTimeout; }
            set
            {
                if (_started)
                    throw new ConfigurationException(
                        "The receive timeout cannot be changed once the bus is in motion. Beep! Beep!");

                _receiveTimeout = value;
            }
        }

        public TimeSpan ShutdownTimeout { get; set; }

        public UntypedChannel EventChannel
        {
            get { return _eventChannel; }
        }

        [UsedImplicitly]
        protected string DebugDisplay
        {
            get { return string.Format("{0}: ", Endpoint.Address); }
        }

        public IEndpointCache EndpointCache { get; private set; }

        public void Dispose()
        {
            Dispose(true);
        }

        public void Publish<T>(T message)
            where T : class
        {
            Publish(message, NoContext);
        }

        /// <summary>
        /// Publishes a message to all subscribed consumers for the message type
        /// </summary>
        /// <typeparam name="T">The type of the message</typeparam>
        /// <param name="message">The messages to be published</param>
        /// <param name="contextCallback">The callback to perform operations on the context</param>
        public void Publish<T>(T message, Action<IPublishContext<T>> contextCallback)
            where T : class
        {
            PublishContext<T> context = ContextStorage.CreatePublishContext(message);
            context.SetSourceAddress(Endpoint.Address.Uri);

            contextCallback(context);

            IList<Exception> exceptions = new List<Exception>();

            int publishedCount = 0;
            foreach (var consumer in OutboundPipeline.Enumerate(context))
            {
                try
                {
                    consumer(context);
                    publishedCount++;
                }
                catch (Exception ex)
                {
                    _log.Error(string.Format("'{0}' threw an exception publishing message '{1}'",
                        consumer.GetType().FullName, message.GetType().FullName), ex);

                    exceptions.Add(ex);
                }
            }

            context.Complete();

            if (publishedCount == 0)
            {
                context.NotifyNoSubscribers();
            }

            _eventChannel.Send(new MessagePublished
                {
                    MessageType = typeof(T),
                    ConsumerCount = publishedCount,
                    Duration = context.Duration,
                });

            if (exceptions.Count > 0)
                throw new PublishException(typeof(T), exceptions);
        }

        public void Publish(object message)
        {
            if (message == null)
                throw new ArgumentNullException("message");

            BusObjectPublisherCache.Instance[message.GetType()].Publish(this, message);
        }

        public void Publish(object message, Type messageType)
        {
            if (message == null)
                throw new ArgumentNullException("message");
            if (messageType == null)
                throw new ArgumentNullException("messageType");

            BusObjectPublisherCache.Instance[messageType].Publish(this, message);
        }

        public void Publish(object message, Action<IPublishContext> contextCallback)
        {
            if (message == null)
                throw new ArgumentNullException("message");
            if (contextCallback == null)
                throw new ArgumentNullException("contextCallback");

            BusObjectPublisherCache.Instance[message.GetType()].Publish(this, message, contextCallback);
        }

        public void Publish(object message, Type messageType, Action<IPublishContext> contextCallback)
        {
            if (message == null)
                throw new ArgumentNullException("message");
            if (messageType == null)
                throw new ArgumentNullException("messageType");
            if (contextCallback == null)
                throw new ArgumentNullException("contextCallback");

            BusObjectPublisherCache.Instance[messageType].Publish(this, message, contextCallback);
        }

        /// <summary>
        /// <see cref="IServiceBus.Publish{T}"/>: this is a "dynamically"
        /// typed overload - give it an interface as its type parameter,
        /// and a loosely typed dictionary of values and the MassTransit
        /// underlying infrastructure will populate an object instance
        /// with the passed values. It actually does this with DynamicProxy
        /// in the background.
        /// </summary>
        /// <typeparam name="T">The type of the interface or
        /// non-sealed class with all-virtual members.</typeparam>
        /// <param name="bus">The bus to publish on.</param>
        /// <param name="values">The dictionary of values to place in the
        /// object instance to implement the interface.</param>
        public void Publish<T>(object values)
            where T : class
        {
            if (values == null)
                throw new ArgumentNullException("values");

            var message = InterfaceImplementationExtensions.InitializeProxy<T>(values);

            Publish(message, x => { });
        }

        /// <summary>
        /// <see cref="Publish{T}(MassTransit.IServiceBus,object)"/>: this
        /// overload further takes an action; it allows you to set <see cref="IPublishContext"/>
        /// meta-data. Also <see cref="IServiceBus.Publish{T}"/>.
        /// </summary>
        /// <typeparam name="T">The type of the message to publish</typeparam>
        /// <param name="bus">The bus to publish the message on.</param>
        /// <param name="values">The dictionary of values to become hydrated and
        /// published under the type of the interface.</param>
        /// <param name="contextCallback">The context callback.</param>
        public void Publish<T>(object values, Action<IPublishContext<T>> contextCallback)
            where T : class
        {
            if (values == null)
                throw new ArgumentNullException("values");

            var message = InterfaceImplementationExtensions.InitializeProxy<T>(values);

            Publish(message, contextCallback);
        }

        public IOutboundMessagePipeline OutboundPipeline { get; private set; }

        public IInboundMessagePipeline InboundPipeline { get; private set; }

        /// <summary>
        /// The endpoint associated with this instance
        /// </summary>
        public IEndpoint Endpoint { get; private set; }

        public UnsubscribeAction Configure(Func<IInboundPipelineConfigurator, UnsubscribeAction> configure)
        {
            return InboundPipeline.Configure(configure);
        }

        [Obsolete("This method is being removed in favor of just using another bus instance.", false)]
        public IServiceBus ControlBus { get; set; }

        public IEndpoint GetEndpoint(Uri address)
        {
            return EndpointCache.GetEndpoint(address);
        }

        public void Inspect(DiagnosticsProbe probe)
        {
            new StandardDiagnosticsInfo().WriteCommonItems(probe);

            probe.Add("mt.version", typeof(IServiceBus).Assembly.GetName().Version);
            probe.Add("mt.receive_from", Endpoint.Address);
            probe.Add("mt.control_bus", ControlBus.Endpoint.Address);
            probe.Add("mt.max_consumer_threads", MaximumConsumerThreads);
            probe.Add("mt.concurrent_receive_threads", ConcurrentReceiveThreads);
            probe.Add("mt.receive_timeout", ReceiveTimeout);

            EndpointCache.Inspect(probe);
            _serviceContainer.Inspect(probe);

            OutboundPipeline.View(pipe => probe.Add("zz.mt.outbound_pipeline", pipe));
            InboundPipeline.View(pipe => probe.Add("zz.mt.inbound_pipeline", pipe));
        }

        public IBusService GetService(Type type)
        {
            return _serviceContainer.GetService(type);
        }

        public bool TryGetService(Type type, out IBusService result)
        {
            return _serviceContainer.TryGetService(type, out result);
        }

        void NoContext<T>(IPublishContext<T> context)
            where T : class
        {
        }

        public void Start()
        {
            if (_started)
                return;

            try
            {
                _serviceContainer.Start();

                _consumerPool = new ThreadPoolConsumerPool(this, _eventChannel, _receiveTimeout)
                    {
                        MaximumConsumerCount = MaximumConsumerThreads,
                    };
                _consumerPool.Start();
            }
            catch (Exception)
            {
                if (_consumerPool != null)
                    _consumerPool.Dispose();

                throw;
            }

            _started = true;
        }

        public void AddService(BusServiceLayer layer, IBusService service)
        {
            _serviceContainer.AddService(layer, service);
        }

        protected virtual void Dispose(bool disposing)
        {
            if (_disposed)
                return;
            if (disposing)
            {
                if (_consumerPool != null)
                {
                    _consumerPool.Stop();
                    _consumerPool.Dispose();
                    _consumerPool = null;
                }

                if (_serviceContainer != null)
                {
                    _serviceContainer.Stop();
                    _serviceContainer.Dispose();
                    _serviceContainer = null;
                }

                if (ControlBus != this)
                    ControlBus.Dispose();

                if (_performanceCounterConnection != null)
                {
                    _performanceCounterConnection.Dispose();
                    _performanceCounterConnection = null;
                }

                _eventChannel = null;

                Endpoint = null;

                if (_counters != null)
                {
                    _counters.Dispose();
                    _counters = null;
                }

                EndpointCache.Dispose();
            }
            _disposed = true;
        }

        void InitializePerformanceCounters()
        {
            try
            {
                string instanceName = string.Format("{0}_{1}{2}",
                    Endpoint.Address.Uri.Scheme, Endpoint.Address.Uri.Host, Endpoint.Address.Uri.AbsolutePath.Replace("/", "_"));

                _counters = new ServiceBusInstancePerformanceCounters(instanceName);

                _performanceCounterConnection = _eventChannel.Connect(x =>
                    {
                        x.AddConsumerOf<MessageReceived>()
                            .UsingConsumer(message =>
                                {
                                    _counters.ReceiveCount.Increment();
                                    _counters.ReceiveRate.Increment();
                                    _counters.ReceiveDuration.IncrementBy(
                                        (long)message.ReceiveDuration.TotalMilliseconds);
                                    _counters.ReceiveDurationBase.Increment();
                                    _counters.ConsumerDuration.IncrementBy(
                                        (long)message.ConsumeDuration.TotalMilliseconds);
                                    _counters.ConsumerDurationBase.Increment();
                                });

                        x.AddConsumerOf<MessagePublished>()
                            .UsingConsumer(message =>
                                {
                                    _counters.PublishCount.Increment();
                                    _counters.PublishRate.Increment();
                                    _counters.PublishDuration.IncrementBy((long)message.Duration.TotalMilliseconds);
                                    _counters.PublishDurationBase.Increment();

                                    _counters.SentCount.IncrementBy(message.ConsumerCount);
                                    _counters.SendRate.IncrementBy(message.ConsumerCount);
                                });

                        x.AddConsumerOf<ThreadPoolEvent>()
                            .UsingConsumer(message =>
                                {
                                    _counters.ReceiveThreadCount.Set(message.ReceiverCount);
                                    _counters.ConsumerThreadCount.Set(message.ConsumerCount);
                                });
                    });
            }
            catch (Exception ex)
            {
                _log.Warn(
                    "The performance counters could not be created, try running the program in the Administrator role. Just once.",
                    ex);
            }
        }
    }
}


text:
/*
 * GET home page.
 */

exports.index = function(req, res){
	var nickname = req.query.nickname,
		playMode = req.app.get('playMode');
  res.render('index', {
		title: 'Bubbles',
		ball: '/images/ball.png',
		nickname: nickname,
		playMode: playMode
	});
};


text:
package org.ehcache.clustered.client;

import org.ehcache.PersistentCacheManager;
import org.ehcache.clustered.client.config.ClusteredStoreConfiguration;
import org.ehcache.clustered.client.config.builders.ClusteredResourcePoolBuilder;
import org.ehcache.clustered.client.config.builders.ClusteringServiceConfigurationBuilder;
import org.ehcache.clustered.client.internal.UnitTestConnectionService;
import org.ehcache.clustered.common.Consistency;
import org.ehcache.config.builders.CacheConfigurationBuilder;
import org.ehcache.config.builders.CacheManagerBuilder;
import org.ehcache.config.builders.ResourcePoolsBuilder;
import org.ehcache.config.units.MemoryUnit;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicReference;

/**
 * This test makes sure a clustered cache can be opened from many client instances. As usual with concurrency tests, a
 * success doesn't mean it will work forever and a failure might not occur reliably. However, it puts together all
 * conditions to make it fail in case of race condition
 *
 * @author Henri Tremblay
 */
public class ClusteredConcurrencyTest {

  private static final URI CLUSTER_URI = URI.create("terracotta://example.com:9540/my-application");
  private static final String CACHE_NAME = "clustered-cache";

  private AtomicReference<Throwable> exception = new AtomicReference<>();

  @Before
  public void definePassthroughServer() throws Exception {
    UnitTestConnectionService.add(CLUSTER_URI,
      new UnitTestConnectionService.PassthroughServerBuilder()
        .resource("primary-server-resource", 64, MemoryUnit.MB)
        .resource("secondary-server-resource", 64, MemoryUnit.MB)
        .build());
  }

  @After
  public void removePassthroughServer() throws Exception {
    UnitTestConnectionService.remove(CLUSTER_URI);
  }

  @Test
  public void test() throws Throwable {
    final int THREAD_NUM = 50;

    final CountDownLatch latch = new CountDownLatch(THREAD_NUM + 1);

    List<Thread> threads = new ArrayList<>(THREAD_NUM);
    for (int i = 0; i < THREAD_NUM; i++) {
      Thread t1 = new Thread(content(latch));
      t1.start();
      threads.add(t1);
    }

    latch.countDown();
    latch.await();

    for(Thread t : threads) {
      t.join();
    }

    Throwable throwable = exception.get();
    if(throwable != null) {
      throw throwable;
    }
  }

  private Runnable content(final CountDownLatch latch) {
    return () -> {
      try {
        CacheManagerBuilder<PersistentCacheManager> clusteredCacheManagerBuilder = CacheManagerBuilder.newCacheManagerBuilder()
          .with(ClusteringServiceConfigurationBuilder.cluster(CLUSTER_URI).autoCreate()
            .defaultServerResource("primary-server-resource")
            .resourcePool("resource-pool-a", 8, MemoryUnit.MB)
            .resourcePool("resource-pool-b", 8, MemoryUnit.MB, "secondary-server-resource"))
          .withCache(CACHE_NAME, CacheConfigurationBuilder.newCacheConfigurationBuilder(Long.class, String.class,
            ResourcePoolsBuilder.newResourcePoolsBuilder()
              .with(ClusteredResourcePoolBuilder.clusteredDedicated("primary-server-resource", 8, MemoryUnit.MB)))
            .add(new ClusteredStoreConfiguration(Consistency.STRONG)));

        latch.countDown();
        try {
          latch.await();
        } catch (InterruptedException e) {
          // continue
        }

        clusteredCacheManagerBuilder.build(true);
      } catch (Throwable t) {
        exception.compareAndSet(null, t); // only keep the first exception
      }
    };
  }
}


text:
<?php
session_start();
require_once("twitteroauth/twitteroauth/twitteroauth.php"); //Path to twitteroauth library

$twitteruser = "DESIGNJORDAN";
$notweets = 30;
$consumerkey = "Hjc4hU1RTr9yeau0s4OrXbHFV";
$consumersecret = "6xfPcRE1jv7jlO8sgXWguu2OdoVMk4mmndKBhKPpoYazcOe0ur";
$accesstoken = "2484115562-s7fn9nPaBFlcrn8irSiyp0LOyvWrVLv1CiYJHVD";
$accesstokensecret = "xvQGcqCGJfnWwrBKQSLagRlK5urcfuhjN7G1WelkyNh0s";

function getConnectionWithAccessToken($cons_key, $cons_secret, $oauth_token, $oauth_token_secret) {
  $connection = new TwitterOAuth($cons_key, $cons_secret, $oauth_token, $oauth_token_secret);
  return $connection;
}

$connection = getConnectionWithAccessToken($consumerkey, $consumersecret, $accesstoken, $accesstokensecret);

$tweets = $connection->get("https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=".$twitteruser."&count=".$notweets);

echo json_encode($tweets);
?>


text:
A string containing binary data.

The BinaryString type is a string that correctly handles binary data
when encoded.