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

package com.google.testing.junit.runner;

import com.google.testing.junit.runner.internal.StackTraces;
import com.google.testing.junit.runner.junit4.JUnit4InstanceModules.Config;
import com.google.testing.junit.runner.junit4.JUnit4InstanceModules.SuiteClass;
import com.google.testing.junit.runner.junit4.JUnit4Runner;
import java.io.PrintStream;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * A class to run JUnit tests in a controlled environment.
 *
 *
Currently sets up a security manager to catch undesirable behaviour; System.exit. Also has
 * nice command line options - run with "-help" for details.
 *
 *
This class traps writes to System.err.println() and System.out.println()
 *  including the output of failed tests in the error report.
 *
 *
It also traps SIGTERM signals to make sure that the test report is written when the signal is
 * closed by the unit test framework for running over time.
 */
public class BazelTestRunner {
  /**
   * If no arguments are passed on the command line, use this System property to
   * determine which test suite to run.
   */
  static final String TEST_SUITE_PROPERTY_NAME = "bazel.test_suite";

  private BazelTestRunner() {
    // utility class; should not be instantiated
  }

  /**
   * Takes as arguments the classes or packages to test.
   *
   *
To help just run one test or method in a suite, the test suite
   * may be passed in via system properties (-Dbazel.test_suite).
   * An empty args parameter means to run all tests in the suite.
   * A non-empty args parameter means to run only the specified tests/methods.
   *
   *
Return codes:
   *

   *
Test runner failure, bad arguments, etc.: exit code of 2

   *
Normal test failure: exit code of 1

   *
All tests pass: exit code of 0

   *

   */
  public static void main(String[] args) {
    PrintStream stderr = System.err;

    String suiteClassName = System.getProperty(TEST_SUITE_PROPERTY_NAME);
    if (!checkTestSuiteProperty(suiteClassName)) {
      System.exit(2);
    }

    if (PersistentTestRunner.isPersistentTestRunner()) {
      System.exit(
          PersistentTestRunner.runPersistentTestRunner(
              suiteClassName,
              System.getenv("WORKSPACE_PREFIX"),
              (suitClass, testArgs, classLoader, resolve) ->
                  runTestsInSuite(suitClass, testArgs, classLoader, resolve)));
    }

    int exitCode;
    try {
      exitCode =
          runTestsInSuite(suiteClassName, args, /* classLoader= */ null, /* resolve =*/ false);
    } catch (Throwable e) {
      // An exception was thrown by the runner. Print the error to the output stream so it will be
      // logged
      // by the executing strategy, and return a failure, so this process can gracefully shut down.
      e.printStackTrace();
      exitCode = 1;
    }

    System.err.printf("%nBazelTestRunner exiting with a return value of %d%n", exitCode);
    System.err.println("JVM shutdown hooks (if any) will run now.");
    System.err.println("The JVM will exit once they complete.");
    System.err.println();

    printStackTracesIfJvmExitHangs(stderr);

    DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    Date shutdownTime = new Date();
    String formattedShutdownTime = format.format(shutdownTime);
    System.err.printf("-- JVM shutdown starting at %s --%n%n", formattedShutdownTime);
    System.exit(exitCode);
  }

  /**
   * Ensures that the bazel.test_suite in argument is not {@code null} or print error and
   * explanation.
   *
   * @param testSuiteProperty system property to check
   */
  private static boolean checkTestSuiteProperty(String testSuiteProperty) {
    if (testSuiteProperty == null) {
      System.err.printf(
          "Error: The test suite Java system property %s is required but missing.%n",
          TEST_SUITE_PROPERTY_NAME);
      System.err.println();
      System.err.println("This property is set automatically when running with Bazel like such:");
      System.err.printf("  java -D%s=[test-suite-class] %s%n",
          TEST_SUITE_PROPERTY_NAME, BazelTestRunner.class.getName());
      System.err.printf("  java -D%s=[test-suite-class] -jar [deploy-jar]%n",
          TEST_SUITE_PROPERTY_NAME);
      System.err.println("E.g.:");
      System.err.printf("  java -D%s=org.example.testing.junit.runner.SmallTests %s%n",
          TEST_SUITE_PROPERTY_NAME, BazelTestRunner.class.getName());
      System.err.printf("  java -D%s=org.example.testing.junit.runner.SmallTests "
              + "-jar SmallTests_deploy.jar%n",
          TEST_SUITE_PROPERTY_NAME);
      return false;
    }
    return true;
  }

  /**
   * Runs the tests in the specified suite. Looks for the suite class in the given classLoader, or
   * in the system classloader if none is specified.
   */
  private static int runTestsInSuite(
      String suiteClassName, String[] args, ClassLoader classLoader, boolean resolve) {
    Class<?> suite = PersistentTestRunner.getTestClass(suiteClassName, classLoader, resolve);

    if (suite == null) {
      // No class found corresponding to the system property passed in from Bazel
      if (args.length == 0 && suiteClassName != null) {
        System.err.printf("Class not found: [%s]%n", suiteClassName);
        return 2;
      }
    }

    // TODO(kush): Use a new classloader for the following instantiation.
    JUnit4Runner runner =
        JUnit4Bazel.builder()
            .suiteClass(new SuiteClass(suite))
            .config(new Config(args))
            .build()
            .runner();
    return runner.run().wasSuccessful() ? 0 : 1;
  }

  /**
   * Prints out stack traces if the JVM does not exit quickly. This can help detect shutdown hooks
   * that are preventing the JVM from exiting quickly.
   *
   * @param out Print stream to use
   */
  private static void printStackTracesIfJvmExitHangs(final PrintStream out) {
    Thread thread = new Thread(new Runnable() {
      @Override
      public void run() {
        sleepUninterruptibly(5);
        out.println("JVM still up after five seconds. Dumping stack traces for all threads.");
        StackTraces.printAll(out);
      }
    }, "BazelTestRunner: Print stack traces if JVM exit hangs");

    thread.setDaemon(true);
    thread.start();
  }

  /**
   * Invokes SECONDS.{@link TimeUnit#sleep(long) sleep(sleepForSeconds)} uninterruptibly.
   */
  private static void sleepUninterruptibly(long sleepForSeconds) {
    boolean interrupted = false;
    try {
      long end = System.nanoTime() + TimeUnit.SECONDS.toNanos(sleepForSeconds);
      while (true) {
        try {
          // TimeUnit.sleep() treats negative timeouts just like zero.
          TimeUnit.NANOSECONDS.sleep(end - System.nanoTime());
          return;
        } catch (InterruptedException e) {
          interrupted = true;
        }
      }
    } finally {
      if (interrupted) {
        Thread.currentThread().interrupt();
      }
    }
  }
}


text:
[Mongo documentation <i class="fa fa-external-link" style="position: relative; top: 2px;" />](http://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html#group)

Run a group command across a collection.

#### Arguments

1. `keys` *(object | array | function)* - An object, array or function expressing the keys to group by.

2. `condition` *(Object)* - An optional condition that must be true for a row to be considered.

3. `initial` *(Object)* - Initial value of the aggregation counter object.

4. `reduce` *(Function)* - The reduce function aggregates (reduces) the objects iterated.

5. [`finalize`] *(Function)* - An optional function to be run on each item in the result set just before the item is returned.

6. [`command`] *(Boolean)* - Specify if you wish to run using the internal group command or using eval, default is true.

7. [`options`] *(Object)*

8. [`callback`] *(function)*

#### Returns

A promise.

#### Example

```js
users.group(
  { a: true },
  {},
  { count: 0 },
  function (obj, prev) {
    prev.count++
  },
  true
)
```

redpajama_set_name: RedPajamaGithub


text:
from cifparser.parser import parse_file

from cifparser.path import Path, make_path, ROOT_PATH

from cifparser.valuetree import ValueTree, load, dump

from cifparser.namespace import Namespace, or_default

from cifparser.version import versionstring


text:
package com.microsoft.azure.management.containerinstance.v2019_12_01;

import com.fasterxml.jackson.annotation.JsonProperty;

/**
 * The GPU resource.
 */
public class GpuResource {
    /**
     * The count of the GPU resource.
     */
    @JsonProperty(value = "count", required = true)
    private int count;

    /**
     * The SKU of the GPU resource. Possible values include: 'K80', 'P100',
     * 'V100'.
     */
    @JsonProperty(value = "sku", required = true)
    private GpuSku sku;

    /**
     * Get the count of the GPU resource.
     *
     * @return the count value
     */
    public int count() {
        return this.count;
    }

    /**
     * Set the count of the GPU resource.
     *
     * @param count the count value to set
     * @return the GpuResource object itself.
     */
    public GpuResource withCount(int count) {
        this.count = count;
        return this;
    }

    /**
     * Get the SKU of the GPU resource. Possible values include: 'K80', 'P100', 'V100'.
     *
     * @return the sku value
     */
    public GpuSku sku() {
        return this.sku;
    }

    /**
     * Set the SKU of the GPU resource. Possible values include: 'K80', 'P100', 'V100'.
     *
     * @param sku the sku value to set
     * @return the GpuResource object itself.
     */
    public GpuResource withSku(GpuSku sku) {
        this.sku = sku;
        return this;
    }

}


text:
namespace metaforce {

class CPakFile : public CDvdFile {
  friend class CResLoader;

public:
  struct SResInfo {
    CAssetId x0_id;
    bool x4_compressed : 1;
    CFactoryMgr::ETypeTable x4_typeIdx;
    u32 x5_offsetDiv32 : 27;
    u32 x7_sizeDiv32 : 27;
    SResInfo(CAssetId id, FourCC fcc, u32 offset, u32 size, u32 flags) : x0_id(id) {
      x4_compressed = flags != 0;
      x4_typeIdx = CFactoryMgr::FourCCToTypeIdx(fcc);
      x5_offsetDiv32 = offset / 32;
      x7_sizeDiv32 = size / 32;
    }
    u32 GetOffset() const { return x5_offsetDiv32 * 32; }
    u32 GetSize() const { return x7_sizeDiv32 * 32; }
    FourCC GetType() const { return CFactoryMgr::TypeIdxToFourCC(x4_typeIdx); }
    bool IsCompressed() const { return x4_compressed; }
    CAssetId GetId() const { return x0_id; }
  };

private:
  bool x28_24_buildDepList : 1;
  bool x28_25_aramFile : 1 = false;
  bool x28_26_worldPak : 1;
  bool x28_27_stashedInARAM : 1 = false;
  bool m_override : 1;
  enum class EAsyncPhase {
    Warmup = 0,
    InitialHeader = 1,
    DataLoad = 2,
    Loaded = 3
  } x2c_asyncLoadPhase = EAsyncPhase::Warmup;
  std::shared_ptr<IDvdRequest> x30_dvdReq; // Used to be auto_ptr
  std::vector<u8> x38_headerData;
  u32 x48_resTableOffset = 0;
  u32 x4c_resTableCount = 0;
  int x50_aramBase = -1;
  std::vector<std::pair<std::string, SObjectTag>> x54_nameList;
  std::vector<CAssetId> x64_depList;
  std::vector<SResInfo> x74_resList;
  mutable s32 x84_currentSeek = -1;
  CAssetId m_mlvlId;
  void LoadResourceTable(athena::io::MemoryReader& r);
  void DataLoad();
  void InitialHeaderLoad();
  void Warmup();

public:
  CPakFile(std::string_view filename, bool buildDepList, bool worldPak, bool override=false);
  ~CPakFile();
  const std::vector<std::pair<std::string, SObjectTag>>& GetNameList() const { return x54_nameList; }
  const std::vector<CAssetId>& GetDepList() const { return x64_depList; }
  const SObjectTag* GetResIdByName(std::string_view name) const;
  const SResInfo* GetResInfoForLoadPreferForward(CAssetId id) const;
  const SResInfo* GetResInfoForLoadDirectionless(CAssetId id) const;
  const SResInfo* GetResInfo(CAssetId id) const;
  bool IsWorldPak() const { return x28_26_worldPak; }
  bool IsOverridePak() const { return m_override; }
  u32 GetFakeStaticSize() const { return 0; }
  void AsyncIdle();
  CAssetId GetMLVLId() const { return m_mlvlId; }
};

} // namespace metaforce


text:
<?php
namespace V2\Core\Utils;

class RenderTime
{
    const PRECISION_SECOND      = 0;
    const PRECISION_MILLISECOND = 1;
    const PRECISION_MICROSECOND = 2;

    private $start;
    private $end;
    private $format = "d/m/y H:i:s";

    public function __construct($autoinit = true)
    {
        $this->start      = null;
        $this->end        = null;
        $this->start_time = null;
        $this->end_time   = null;
        if ($autoinit) {
            $this->start();
        }
    }

    public function start()
    {
        $this->start      = microtime(true);
        $this->start_time = time();
        $this->end        = null;
        return $this;
    }
    public function date($time = null)
    {
        return date($this->getFormat(), $time ?: time());
    }
    public function date_start()
    {
        is_null($this->start_time) && $this->start();
        return $this->date($this->start_time);
    }
    public function date_end()
    {
        if (is_null($this->start_time)) {
            return 'Can\'t return the render time';
        }

        is_null($this->end_time) && $this->end();
        return $this->date($this->end_time);
    }
    public function setFormat($format)
    {
        $this->format = $format;
    }
    public function getFormat()
    {
        return $this->format;
    }
    public function end()
    {
        $this->end      = microtime(true);
        $this->end_time = time();
        return $this;
    }
    public function getStarTime()
    {
        return $this->start_time;
    }
    public function duration()
    {
        if (is_null($this->start_time)) {
            return 'Can\'t return the render time';
        }
        if (is_null($this->end_time)) {
            $this->end();
        }
        $secs = $this->end_time - $this->start_time;
        $bit  = array(
            'y' => $secs / 31556926 % 12,
            'w' => $secs / 604800 % 52,
            'd' => $secs / 86400 % 7,
            'h' => $secs / 3600 % 24,
            'm' => $secs / 60 % 60,
            's' => $secs % 60,
        );
        $ret = [];
        foreach ($bit as $k => $v) {
            if ($v > 0) {
                $ret[] = $v . $k;
            }
        }

        return join(' ', $ret);
    }

    /**
     * This function return the time the code use to process
     * @param $precision the precision wanted, with const. second, millisecond and microsecond available (default PRECISION_MILLISECOND)
     * @param $floatingPrecision the number of numbers after the floating point (default 0)
     * @param $showUnit precise if the unit should be returned (default true)
     * @return the render time in the precision asked. Note that the precision is ±0.5 the precision (eq. 5s is at least 4.5s and at most 5.5s) <br/>
     * The code have an error about 2 or 3µs (time to execute the end function)
     */
    public function getRenderTime($precision = self::PRECISION_SECOND, $floatingPrecision = 2, $showUnit = true)
    {

        $test = is_int($precision) && $precision >= self::PRECISION_SECOND && $precision <= self::PRECISION_MICROSECOND &&
        is_float($this->start) && is_float($this->end) && $this->start <= $this->end &&
        is_int($floatingPrecision) && $floatingPrecision >= 0 &&
        is_bool($showUnit);

        if ($test) {
            $duration = round(($this->end - $this->start) * 10 ** ($precision * 3), $floatingPrecision);

            if ($showUnit) {
                return $duration . ' ' . self::getUnit($precision);
            } else {
                return $duration;
            }

        } else {
            return 'Can\'t return the render time';
        }
    }
    public function __toString()
    {
        return $this->duration();
    }

    private static function getUnit($precision)
    {
        switch ($precision) {
            case self::PRECISION_SECOND:
                return 's';
            case self::PRECISION_MILLISECOND:
                return 'ms';
            case self::PRECISION_MICROSECOND:
                return 'µs';
            default:
                return '(no unit)';
        }
    }
}


text:
//
//  SDFAssetsLibraryDemoViewController.m
//  DFImageManagerSample
//
//  Created by Alexander Grebenyuk on 1/7/15.
//  Copyright (c) 2015 Alexander Grebenyuk. All rights reserved.
//

#import "SDFAssetsLibraryDemoViewController.h"
#import <AssetsLibrary/AssetsLibrary.h>
#import <DFImageManager/DFImageManagerKit.h>
#import "UIViewController+SDFImageManager.h"

static NSString * const reuseIdentifier = @"Cell";

@interface SDFAssetsLibraryDemoViewController () <DFCollectionViewPreheatingControllerDelegate>

@end

@implementation SDFAssetsLibraryDemoViewController {
    NSArray /* NSURL */ *_photos;
    UIActivityIndicatorView *_activity;
    DFCollectionViewPreheatingController *_preheatingController;
}

- (void)viewDidLoad {
    [super viewDidLoad];

    [self.collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:reuseIdentifier];
}

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

    ALAuthorizationStatus authorizationStatus = [ALAssetsLibrary authorizationStatus];
    switch (authorizationStatus) {
        case ALAuthorizationStatusAuthorized:
            [self _loadAssets];
            break;
        case ALAuthorizationStatusDenied:
        case ALAuthorizationStatusRestricted:
            [self _showErrorMessageForDeniedPhotoLibraryAccess];
            break;
        case ALAuthorizationStatusNotDetermined: {
            [self _loadAssets];
        }
            break;
        default:
            break;
    }
}

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

    _preheatingController = [[DFCollectionViewPreheatingController alloc] initWithCollectionView:self.collectionView];
    _preheatingController.delegate = self;
    [_preheatingController updatePreheatRect];
}

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

    // Resets preheat rect and stop preheating images via delegate call.
    [_preheatingController resetPreheatRect];
    _preheatingController = nil;
}

- (void)_loadAssets {
    _activity = [self df_showActivityIndicatorView];

    SDFAssetsLibraryDemoViewController *__weak weakSelf = self;
    NSMutableArray *assets = [NSMutableArray new];
    [[DFAssetsLibraryImageFetcher defaulLibrary] enumerateGroupsWithTypes:ALAssetsGroupSavedPhotos usingBlock:^(ALAssetsGroup *group, BOOL *stop) {
        [group enumerateAssetsUsingBlock:^(ALAsset *result, NSUInteger index, BOOL *stop) {
            NSString *assetType = [result valueForProperty:ALAssetPropertyType];
            if ([assetType isEqual:ALAssetTypePhoto]) {
                /*!
                 The example of DFALAsset usage
                DFALAsset *wrapper = [[DFALAsset alloc] initWithAsset:result];
                // For more info about DLALAsset and warmup methods see DFAssetsLibraryImageFetcher docs.
                [wrapper warmup];
                if (wrapper) {
                    [assets addObject:wrapper];
                }
                 */

                NSURL *assetURL = [result valueForProperty:ALAssetPropertyAssetURL];
                if (assetURL) {
                    [assets addObject:assetURL];
                }
            }
        }];
        if (group == nil) { // Enumeration is done
            [self _didLoadAssets:assets];
        }
    } failureBlock:^(NSError *error) {
        [weakSelf _didFailWithError:error];
    }];
}

- (void)_didLoadAssets:(NSArray *)assets {
    [_activity removeFromSuperview];
    _photos = assets;
    [self.collectionView reloadData];
}

- (void)_didFailWithError:(NSError *)error {
    [_activity removeFromSuperview];
    if (error.code == ALAssetsLibraryAccessUserDeniedError) {
        [self _showErrorMessageForDeniedPhotoLibraryAccess];
    }
}

- (void)_showErrorMessageForDeniedPhotoLibraryAccess {
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Photo library access denied." message:nil delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil];
    [alert show];
}

#pragma mark - <UICollectionViewDataSource>

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return _photos.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:reuseIdentifier forIndexPath:indexPath];
    cell.backgroundColor = [UIColor colorWithWhite:235.f/255.f alpha:1.f];

    DFImageView *imageView = (id)[cell viewWithTag:15];
    if (!imageView) {
        imageView = [[DFImageView alloc] initWithFrame:cell.bounds];
        imageView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
        imageView.tag = 15;
        [cell addSubview:imageView];
    }

    NSURL *assetURL = _photos[indexPath.row];
    [imageView prepareForReuse];
    [imageView setImageWithResource:assetURL];

    return cell;
}

#pragma mark - <DFCollectionViewPreheatingControllerDelegate>

- (void)collectionViewPreheatingController:(DFCollectionViewPreheatingController *)controller didUpdatePreheatRectWithAddedIndexPaths:(NSArray *)addedIndexPaths removedIndexPaths:(NSArray *)removedIndexPaths {
    [[DFImageManager sharedManager] startPreheatingImagesForRequests:[self _imageRequestsAtIndexPaths:addedIndexPaths]];
    [[DFImageManager sharedManager] stopPreheatingImagesForRequests:[self _imageRequestsAtIndexPaths:removedIndexPaths]];
}

- (NSArray *)_imageRequestsAtIndexPaths:(NSArray *)indexPaths {
    UICollectionViewFlowLayout *layout = (id)self.collectionViewLayout;
    CGSize targetSize = ({
        CGFloat scale = [UIScreen mainScreen].scale;
        CGSizeMake(layout.itemSize.width * scale, layout.itemSize.height * scale);
    });
    NSMutableArray *requests = [NSMutableArray new];
    for (NSIndexPath *indexPath in indexPaths) {
        NSURL *assetURL = _photos[indexPath.row];
        [requests addObject:[DFImageRequest requestWithResource:assetURL targetSize:targetSize contentMode:DFImageContentModeAspectFill options:nil]];
    }
    return requests;
}

@end


text:
package responses

import (
	"github.com/baocaixiong/kdtgo"
)

// 单笔交易详情
type TradeDetail struct {
	kdtgo.Body
	Response struct {
		Trade Trade `json:"trade"`
	} `json:"response"`
}

// 卖家关闭单个交易
type TradeClose TradeDetail

// 卖家修改一笔交易备注
type TradeMemoUpdate TradeDetail

//查询卖家已卖出的交易列表
type TradesSold struct {
	kdtgo.Body
	Response struct {
		TotalResults float64 `json:"total_results"`
		Trades       []Trade `json:"trades"`
	} `json:"response"`
}

type Trade struct {
	BuyerArea     string  `json:"buyer_area"`
	BuyerID       float64 `json:"buyer_id"`
	BuyerMessage  string  `json:"buyer_message"`
	BuyerNick     string  `json:"buyer_nick"`
	BuyerType     float64 `json:"buyer_type"`
	ConsignTime   string  `json:"consign_time"`
	CouponDetails []struct {
		CouponCondition   string `json:"coupon_condition"`
		CouponContent     string `json:"coupon_content"`
		CouponDescription string `json:"coupon_description"`
		CouponID          string `json:"coupon_id"`
		CouponName        string `json:"coupon_name"`
		CouponType        string `json:"coupon_type"`
		DiscountFee       string `json:"discount_fee"`
		UsedAt            string `json:"used_at"`
	} `json:"coupon_details"`
	Created     string  `json:"created"`
	DiscountFee float64 `json:"discount_fee"`
	Feedback    string  `json:"feedback"`
	FetchDetail struct {
		FetchTime     string `json:"fetch_time"`
		FetcherMobile string `json:"fetcher_mobile"`
		FetcherName   string `json:"fetcher_name"`
		ShopAddress   string `json:"shop_address"`
		ShopCity      string `json:"shop_city"`
		ShopDistrict  string `json:"shop_district"`
		ShopMobile    string `json:"shop_mobile"`
		ShopName      string `json:"shop_name"`
		ShopState     string `json:"shop_state"`
	} `json:"fetch_detail"`
	Num    float64 `json:"num"`
	NumIid float64 `json:"num_iid"`
	Orders []struct {
		BuyerMessages []struct {
			Content string `json:"content"`
			Title   string `json:"title"`
		} `json:"buyer_messages"`
		DiscountFee       float64 `json:"discount_fee"`
		Num               float64 `json:"num"`
		NumIid            float64 `json:"num_iid"`
		OuterItemID       string  `json:"outer_item_id"`
		OuterSkuID        string  `json:"outer_sku_id"`
		Payment           float64 `json:"payment"`
		PicPath           string  `json:"pic_path"`
		PicThumbPath      string  `json:"pic_thumb_path"`
		Price             float64 `json:"price"`
		SellerNick        string  `json:"seller_nick"`
		SkuID             float64 `json:"sku_id"`
		SkuPropertiesName string  `json:"sku_properties_name"`
		Title             string  `json:"title"`
		TotalFee          float64 `json:"total_fee"`
	} `json:"orders"`
	OuterTid         string  `json:"outer_tid"`
	PayTime          string  `json:"pay_time"`
	PayType          string  `json:"pay_type"`
	Payment          float64 `json:"payment"`
	PicPath          string  `json:"pic_path"`
	PicThumbPath     string  `json:"pic_thumb_path"`
	PostFee          float64 `json:"post_fee"`
	Price            float64 `json:"price"`
	ReceiverAddress  string  `json:"receiver_address"`
	ReceiverCity     string  `json:"receiver_city"`
	ReceiverDistrict string  `json:"receiver_district"`
	ReceiverMobile   string  `json:"receiver_mobile"`
	ReceiverName     string  `json:"receiver_name"`
	ReceiverState    string  `json:"receiver_state"`
	ReceiverZip      string  `json:"receiver_zip"`
	SellerFlag       string  `json:"seller_flag"`
	ShippingType     string  `json:"shipping_type"`
	SignTime         string  `json:"sign_time"`
	Status           string  `json:"status"`
	SubTrades        string  `json:"sub_trades"`
	Tid              string  `json:"tid"`
	Title            string  `json:"title"`
	TotalFee         float64 `json:"total_fee"`
	TradeMemo        string  `json:"trade_memo"`
	UpdateTime       string  `json:"update_time"`
	WeixinUserID     float64 `json:"weixin_user_id"`
}


text:
Special Event

StartupWeekend is coming in Montreal for the first time Feb 3rd, 4th and 5th. Entrepreneurs, developers and designers are invited to team up, design, make and launch a start-up in 54 hours, and then present in front of a panel of judges.

If you've ever thought about launching your own web service or want to take on the challenge of building something in a weekend then Montreal StartupWeekend is the perfect place to start!

js-montreal.org and Montreal StartupWeekend are partnering to offer a special discount price to js-montreal members. Email us or message us on Twitter to get a rebate code will give you 66% off! (that's 25$ instead of 75$)


text:
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE23_Relative_Path_Traversal__wchar_t_console_w32CreateFile_83_bad.cpp
Label Definition File: CWE23_Relative_Path_Traversal.label.xml
Template File: sources-sink-83_bad.tmpl.cpp
*/
/*
 * @description
 * CWE: 23 Relative Path Traversal
 * BadSource: console Read input from the console
 * GoodSource: Use a fixed file name
 * Sinks: w32CreateFile
 *    BadSink : Open the file named in data using CreateFile()
 * Flow Variant: 83 Data flow: data passed to class constructor and destructor by declaring the class object on the stack
 *
 * */
#ifndef OMITBAD

#include "std_testcase.h"
#include "CWE23_Relative_Path_Traversal__wchar_t_console_w32CreateFile_83.h"

#include <windows.h>

namespace CWE23_Relative_Path_Traversal__wchar_t_console_w32CreateFile_83
{
CWE23_Relative_Path_Traversal__wchar_t_console_w32CreateFile_83_bad::CWE23_Relative_Path_Traversal__wchar_t_console_w32CreateFile_83_bad(wchar_t * dataCopy)
{
    data = dataCopy;
    {
        /* Read input from the console */
        size_t dataLen = wcslen(data);
        /* if there is room in data, read into it from the console */
        if (FILENAME_MAX-dataLen > 1)
        {
            /* POTENTIAL FLAW: Read data from the console */
            if (fgetws(data+dataLen, (int)(FILENAME_MAX-dataLen), stdin) != NULL)
            {
                /* The next few lines remove the carriage return from the string that is
                 * inserted by fgetws() */
                dataLen = wcslen(data);
                if (dataLen > 0 && data[dataLen-1] == L'\n')
                {
                    data[dataLen-1] = L'\0';
                }
            }
            else
            {
                printLine("fgetws() failed");
                /* Restore NUL terminator if fgetws fails */
                data[dataLen] = L'\0';
            }
        }
    }
}

CWE23_Relative_Path_Traversal__wchar_t_console_w32CreateFile_83_bad::~CWE23_Relative_Path_Traversal__wchar_t_console_w32CreateFile_83_bad()
{
    {
        HANDLE hFile;
        /* POTENTIAL FLAW: Possibly creating and opening a file without validating the file name or path */
        hFile = CreateFileW(data,
                            (GENERIC_WRITE|GENERIC_READ),
                            0,
                            NULL,
                            OPEN_ALWAYS,
                            FILE_ATTRIBUTE_NORMAL,
                            NULL);
        if (hFile != INVALID_HANDLE_VALUE)
        {
            CloseHandle(hFile);
        }
    }
}
}
#endif /* OMITBAD */


text:
.landing {
  position: relative;
  width: 100vw;
  height: 100vh;

  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.landing__background {
  position: absolute;
  top: 0;
  bottom: 0;
  right: 0;
  left: 0;
}

.landing__background img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.paper.landing__paper {
  position: relative;
  z-index: 10;
  width: 80vw;
  max-width: 1000px;
  padding: 0;

  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.landing__logo {
  height: 70px;
  width: 70px;
  margin-top: calc(var(--base-spacing) * 2);
  margin-bottom: var(--base-spacing);
}

.landing__info-icon {
  position: absolute;
  top: var(--base-spacing);
  right: var(--base-spacing);
}

.landing h1 {
  font-size: 28px;
}

.landing__error {
  color: var(--fail-color);
  margin-top: var(--base-spacing);
}

.landing__upload {
  width: 100%;
  display: flex;
  flex-direction: row;

  margin-top: calc(var(--base-spacing) * 2);
  border-top: 1px solid var(--base-border-color);
}


text:
title: Talkshow rubrik Cermin
date: 2012-03-09
categories:
- laporan
- Radio Buruh Perempuan; Dari Perempuan Buruh untuk KesetaraanRadio Buruh Perempuan; Dari Perempuan Buruh untuk Kesetaraan
layout: laporancmb
---

![200px-Maret_09_2012_-_Pelecehan_Seksual_Terhadap_Perempuan.JPG](/uploads/200px-Maret_09_2012_-_Pelecehan_Seksual_Terhadap_Perempuan.JPG	){: .img-responsive .center-block }

![200px-Maret_09_2012_-_pelecehan_seksual_terhadap_perempuan_3-cermin.jpg](/uploads/200px-Maret_09_2012_-_pelecehan_seksual_terhadap_perempuan_3-cermin.jpg){: .img-responsive .center-block }

![200px-Maret_09_2012_-_pelecehan_terhadap_perempuan_1.JPG](/uploads/200px-Maret_09_2012_-_pelecehan_terhadap_perempuan_1.JPG){: .img-responsive .center-block }

![200px-Maret_09_2012-_pelecehan_seksual_terhadap_perempuan_2-cermin.jpg](/uploads/200px-Maret_09_2012-_pelecehan_seksual_terhadap_perempuan_2-cermin.jpg){: .img-responsive .center-block }

**Tujuan** : Talkshow rubrik Cermin

**Lokasi** : Sekretariat Marsinah fm

**Alamat** : Jl. Tipar Selatan XII, No.9, Semper Barat, Jakarta Utara

**Jam** : 19:00 WIB - 20:30 WIB

**Hadir** :
* [Fitri](http://wiki.ciptamedia.org/wiki/Fitri)
* [Christina Yulita](http://wiki.ciptamedia.org/wiki/Christina_Yulita)

**Ringkasan** :
* Materi talkshow ini adalah tentang pelecehan seksual yang sedang marak, cara melawan dan mengatasinya dengan pembicara Christina Yulita dari Komnas Perempuan


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

package cmd

import (
	"os"
	"strings"

	"github.com/fatih/color"
	"github.com/minio/cli"
	"github.com/minio/mc/pkg/console"
)

// stat specific flags.
var (
	statFlags = []cli.Flag{
		cli.BoolFlag{
			Name:  "recursive, r",
			Usage: "Stat recursively.",
		},
		cli.StringFlag{
			Name:  "encrypt-key",
			Usage: "Encrypt/Decrypt (using server-side encryption)",
		},
	}
)

// stat files and folders.
var statCmd = cli.Command{
	Name:   "stat",
	Usage:  "Stat contents of objects and folders.",
	Action: mainStat,
	Before: setGlobalsFromContext,
	Flags:  append(statFlags, globalFlags...),
	CustomHelpTemplate: `NAME:
  {{.HelpName}} - {{.Usage}}

USAGE:
  {{.HelpName}} [FLAGS] TARGET [TARGET ...]

FLAGS:
  {{range .VisibleFlags}}{{.}}
  {{end}}

ENVIRONMENT VARIABLES:
   MC_ENCRYPT_KEY: List of comma delimited prefix=secret values

EXAMPLES:
   1. Stat all contents of mybucket on Amazon S3 cloud storage.
      $ {{.HelpName}} s3/mybucket/

   2. Stat all contents of mybucket on Amazon S3 cloud storage on Microsoft Windows.
      $ {{.HelpName}} s3\mybucket\

   3. Stat files recursively on a local filesystem on Microsoft Windows.
      $ {{.HelpName}} --recursive C:\Users\Worf\

   4. Stat files which are encrypted on the server side
      $ {{.HelpName}} --encrypt-key "s3/ferenginar=32byteslongsecretkeymustbegiven1" s3/ferenginar/klingon_opera_aktuh_maylotah.ogg
`,
}

// checkStatSyntax - validate all the passed arguments
func checkStatSyntax(ctx *cli.Context) {
	if !ctx.Args().Present() {
		cli.ShowCommandHelpAndExit(ctx, "stat", 1) // last argument is exit code
	}

	args := ctx.Args()
	for _, arg := range args {
		if strings.TrimSpace(arg) == "" {
			fatalIf(errInvalidArgument().Trace(args...), "Unable to validate empty argument.")
		}
	}
	// extract URLs.
	URLs := ctx.Args()
	isIncomplete := false
	for _, url := range URLs {
		_, _, err := url2Stat(url)
		if err != nil && !isURLPrefixExists(url, isIncomplete) {
			fatalIf(err.Trace(url), "Unable to stat `"+url+"`.")
		}
	}
}

// mainStat - is a handler for mc stat command
func mainStat(ctx *cli.Context) error {
	// Additional command specific theme customization.
	console.SetColor("Name", color.New(color.Bold, color.FgCyan))
	console.SetColor("Date", color.New(color.FgWhite))
	console.SetColor("Size", color.New(color.FgWhite))
	console.SetColor("ETag", color.New(color.FgWhite))

	console.SetColor("EncryptionHeaders", color.New(color.FgWhite))
	console.SetColor("Metadata", color.New(color.FgWhite))

	// check 'stat' cli arguments.
	checkStatSyntax(ctx)

	// Set command flags from context.
	isRecursive := ctx.Bool("recursive")

	args := ctx.Args()
	// mimic operating system tool behavior.
	if !ctx.Args().Present() {
		args = []string{"."}
	}

	sseKeys := os.Getenv("MC_ENCRYPT_KEY")
	if key := ctx.String("encrypt-key"); key != "" {
		sseKeys = key
	}

	encKeyDB, err := parseAndValidateEncryptionKeys(sseKeys)
	fatalIf(err, "Unable to parse encryption keys.")

	var cErr error
	for _, targetURL := range args {
		var clnt Client
		clnt, err := newClient(targetURL)
		fatalIf(err.Trace(targetURL), "Unable to initialize target `"+targetURL+"`.")

		targetAlias, _, _ := mustExpandAlias(targetURL)
		return doStat(clnt, isRecursive, targetAlias, targetURL, encKeyDB)
	}
	return cErr

}


text:
(function ($) {
  $.fn.selectpicker.defaults = {
    noneSelectedText: 'Hautapenik ez',
    noneResultsText: 'Emaitzarik ez',
    countSelectedText: '{1}(e)tik {0} hautatuta',
    maxOptionsText: ['Mugara iritsita ({n} {var} gehienez)', 'Taldearen mugara iritsita ({n} {var} gehienez)', ['elementu', 'elementu']],
    multipleSeparator: ', '
  };
}(jQuery));


text:
namespace ui {
// A GestureRecognizer is an abstract base class for conversion of touch events
// into gestures.
class EVENTS_EXPORT GestureRecognizer {
 public:
  static GestureRecognizer* Create();
  static GestureRecognizer* Get();

  // List of GestureEvent*.
  typedef ScopedVector<GestureEvent> Gestures;

  virtual ~GestureRecognizer() {}

  // Invoked for each touch event that could contribute to the current gesture.
  // Returns list of zero or more GestureEvents identified after processing
  // TouchEvent.
  // Caller would be responsible for freeing up Gestures.
  virtual Gestures* ProcessTouchEventForGesture(const TouchEvent& event,
                                                ui::EventResult result,
                                                GestureConsumer* consumer) = 0;

  // This is called when the consumer is destroyed. So this should cleanup any
  // internal state maintained for |consumer|.
  virtual void CleanupStateForConsumer(GestureConsumer* consumer) = 0;

  // Return the window which should handle this TouchEvent, in the case where
  // the touch is already associated with a target.
  // Otherwise, returns null.
  virtual GestureConsumer* GetTouchLockedTarget(TouchEvent* event) = 0;

  // Return the window which should handle this GestureEvent.
  virtual GestureConsumer* GetTargetForGestureEvent(GestureEvent* event) = 0;

  // If there is an active touch within
  // GestureConfiguration::max_separation_for_gesture_touches_in_pixels,
  // of |location|, returns the target of the nearest active touch.
  virtual GestureConsumer* GetTargetForLocation(const gfx::Point& location) = 0;

  // Makes |new_consumer| the target for events previously targeting
  // |current_consumer|. All other targets are canceled.
  // The caller is responsible for updating the state of the consumers to
  // be aware of this transfer of control (there are no ENTERED/EXITED events).
  // If |new_consumer| is NULL, all events are canceled.
  // If |old_consumer| is NULL, all events not already targeting |new_consumer|
  // are canceled.
  virtual void TransferEventsTo(GestureConsumer* current_consumer,
                                GestureConsumer* new_consumer) = 0;

  // If a gesture is underway for |consumer| |point| is set to the last touch
  // point and true is returned. If no touch events have been processed for
  // |consumer| false is returned and |point| is untouched.
  virtual bool GetLastTouchPointForTarget(GestureConsumer* consumer,
                                          gfx::Point* point) = 0;

  // Subscribes |helper| for dispatching async gestures such as long press.
  // The Gesture Recognizer does NOT take ownership of |helper| and it is the
  // responsibility of the |helper| to call |RemoveGestureEventHelper()| on
  // destruction.
  virtual void AddGestureEventHelper(GestureEventHelper* helper) = 0;

  // Unsubscribes |helper| from async gesture dispatch.
  // Since the GestureRecognizer does not own the |helper|, it is not deleted
  // and must be cleaned up appropriately by the caller.
  virtual void RemoveGestureEventHelper(GestureEventHelper* helper) = 0;
};

}  // namespace ui

#endif  // UI_EVENTS_GESTURES_GESTURE_RECOGNIZER_H_


text:
package org.apache.jmeter.util;

import java.net.HttpURLConnection;
import java.net.Socket;
import java.security.GeneralSecurityException;
import java.security.Principal;
import java.security.PrivateKey;
import java.security.Provider;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.KeyManager;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.X509KeyManager;
import javax.net.ssl.X509TrustManager;

import org.apache.commons.httpclient.protocol.Protocol;
import org.apache.commons.httpclient.protocol.ProtocolSocketFactory;
import org.apache.jmeter.util.keystore.JmeterKeyStore;
import org.apache.jorphan.logging.LoggingManager;
import org.apache.log.Logger;

/**
 * The SSLManager handles the KeyStore information for JMeter. Basically, it
 * handles all the logic for loading and initializing all the JSSE parameters
 * and selecting the alias to authenticate against if it is available.
 * SSLManager will try to automatically select the client certificate for you,
 * but if it can't make a decision, it will pop open a dialog asking you for
 * more information.
 *
 * TODO: does not actually prompt
 *
 */
public class JsseSSLManager extends SSLManager {
    private static final Logger log = LoggingManager.getLoggerForClass();

    private static final String HTTPS = "https"; // $NON-NLS-1$

    // Temporary fix to allow default protocol to be changed
    private static final String DEFAULT_SSL_PROTOCOL =
        JMeterUtils.getPropDefault("https.default.protocol","TLS"); // $NON-NLS-1$ // $NON-NLS-2$

    // Allow reversion to original shared session context
    private static final boolean SHARED_SESSION_CONTEXT =
        JMeterUtils.getPropDefault("https.sessioncontext.shared",false); // $NON-NLS-1$

    /**
     * Characters per second, used to slow down sockets
     */
    public static final int CPS = JMeterUtils.getPropDefault("httpclient.socket.https.cps", 0); // $NON-NLS-1$

    static {
        log.info("Using default SSL protocol: "+DEFAULT_SSL_PROTOCOL);
        log.info("SSL session context: "+(SHARED_SESSION_CONTEXT ? "shared" : "per-thread"));

        if (CPS > 0) {
            log.info("Setting up HTTPS SlowProtocol, cps="+CPS);
        }

    }

    /**
     * Cache the SecureRandom instance because it takes a long time to create
     */
    private SecureRandom rand;

    private Provider pro = null; // TODO why not use the super class value?

    private SSLContext defaultContext; // If we are using a single session
    private ThreadLocal<SSLContext> threadlocal; // Otherwise

    /**
     * Create the SSLContext, and wrap all the X509KeyManagers with
     * our X509KeyManager so that we can choose our alias.
     *
     * @param provider
     *            Description of Parameter
     */
    public JsseSSLManager(Provider provider) {
        log.debug("ssl Provider =  " + provider);
        setProvider(provider);
        if (null == this.rand) { // Surely this is always null in the constructor?
            this.rand = new SecureRandom();
        }
        try {
            if (SHARED_SESSION_CONTEXT) {
                log.debug("Creating shared context");
                this.defaultContext = createContext();
            } else {
                this.threadlocal = new ThreadLocal<SSLContext>();
            }

            HttpsURLConnection.setDefaultSSLSocketFactory(new HttpSSLProtocolSocketFactory(this, CPS));
            HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
                @Override
                public boolean verify(String hostname, SSLSession session) {
                    return true;
                }
            });

            /*
             * Also set up HttpClient defaults
             */
            Protocol protocol = new Protocol(
                    JsseSSLManager.HTTPS,
                    (ProtocolSocketFactory) new HttpSSLProtocolSocketFactory(this, CPS),
                    443);
            Protocol.registerProtocol(JsseSSLManager.HTTPS, protocol);
            log.debug("SSL stuff all set");
        } catch (GeneralSecurityException ex) {
            log.error("Could not set up SSLContext", ex);
        }
        log.debug("JsseSSLManager installed");
    }

    /**
     * Sets the Context attribute of the JsseSSLManager object
     *
     * @param conn
     *            The new Context value
     */
    @Override
    public void setContext(HttpURLConnection conn) {
        if (conn instanceof HttpsURLConnection) {
/*
 * No point doing this on a per-connection basis, as there is currently no way to configure it.
 * So we leave it to the defaults set up in the SSL Context
 *
 */
//          HttpsURLConnection secureConn = (HttpsURLConnection) conn;
//          secureConn.setSSLSocketFactory(this.getContext().getSocketFactory());
        } else {
            log.warn("Unexpected HttpURLConnection class: "+conn.getClass().getName());
        }
    }

    /**
     * Sets the Provider attribute of the JsseSSLManager object
     *
     * @param p
     *            The new Provider value
     */
    @Override
    protected final void setProvider(Provider p) {
        super.setProvider(p);
        if (null == this.pro) {
            this.pro = p;
        }
    }

    /**
     * Returns the SSLContext we are using.
     * This is either a context per thread,
     * or, for backwards compatibility, a single shared context.
     *
     * @return The Context value
     */
    public SSLContext getContext() throws GeneralSecurityException {
        if (SHARED_SESSION_CONTEXT) {
            if (log.isDebugEnabled()){
                log.debug("Using shared SSL context for: "+Thread.currentThread().getName());
            }
            return this.defaultContext;
        }

        SSLContext sslContext = this.threadlocal.get();
        if (sslContext == null) {
            if (log.isDebugEnabled()){
                log.debug("Creating threadLocal SSL context for: "+Thread.currentThread().getName());
            }
            sslContext = createContext();
            this.threadlocal.set(sslContext);
        }
        if (log.isDebugEnabled()){
            log.debug("Using threadLocal SSL context for: "+Thread.currentThread().getName());
        }
        return sslContext;
    }

    /**
     * Resets the SSLContext if using per-thread contexts.
     *
     */
    public void resetContext() {
        if (!SHARED_SESSION_CONTEXT) {
            log.debug("Clearing session context for current thread");
            this.threadlocal.set(null);
        }
    }
    /*
     *
     * Creates new SSL context
     * @return SSL context
     * @throws GeneralSecurityException
     */
    private SSLContext createContext() throws GeneralSecurityException {
        SSLContext context;
        if (pro != null) {
            context = SSLContext.getInstance(DEFAULT_SSL_PROTOCOL, pro); // $NON-NLS-1$
        } else {
            context = SSLContext.getInstance(DEFAULT_SSL_PROTOCOL); // $NON-NLS-1$
        }
        KeyManagerFactory managerFactory =
            KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        JmeterKeyStore keys = this.getKeyStore();
        managerFactory.init(null, defaultpw == null ? new char[]{} : defaultpw.toCharArray());
        KeyManager[] managers = managerFactory.getKeyManagers();
        KeyManager[] newManagers = new KeyManager[managers.length];

        log.debug(keys.getClass().toString());

        // Now wrap the default managers with our key manager
        for (int i = 0; i < managers.length; i++) {
            if (managers[i] instanceof X509KeyManager) {
                X509KeyManager manager = (X509KeyManager) managers[i];
                newManagers[i] = new WrappedX509KeyManager(manager, keys);
            } else {
                newManagers[i] = managers[i];
            }
        }

        // Get the default trust managers
        TrustManagerFactory tmfactory = TrustManagerFactory.getInstance(
                TrustManagerFactory.getDefaultAlgorithm());
        tmfactory.init(this.getTrustStore());

        // Wrap the defaults in our custom trust manager
        TrustManager[] trustmanagers = tmfactory.getTrustManagers();
        for (int i = 0; i < trustmanagers.length; i++) {
            if (trustmanagers[i] instanceof X509TrustManager) {
                trustmanagers[i] = new CustomX509TrustManager(
                    (X509TrustManager)trustmanagers[i]);
            }
        }
        context.init(newManagers, trustmanagers, this.rand);
        if (log.isDebugEnabled()){
            String[] dCiphers = context.getSocketFactory().getDefaultCipherSuites();
            String[] sCiphers = context.getSocketFactory().getSupportedCipherSuites();
            int len = (dCiphers.length > sCiphers.length) ? dCiphers.length : sCiphers.length;
            for (int i = 0; i < len; i++) {
                if (i < dCiphers.length) {
                    log.debug("Default Cipher: " + dCiphers[i]);
                }
                if (i < sCiphers.length) {
                    log.debug("Supported Cipher: " + sCiphers[i]);
                }
            }
        }
        return context;
    }

    /**
     * This is the X509KeyManager we have defined for the sole purpose of
     * selecting the proper key and certificate based on the keystore available.
     *
     */
    private static class WrappedX509KeyManager implements X509KeyManager {

        /**
         * The parent X509KeyManager.
         * This is used for the methods {@link #getServerAliases(String, Principal[])}
         *  and {@link #chooseServerAlias(String, Principal[], Socket)}
         */
        private final X509KeyManager manager;

        /**
         * The KeyStore this KeyManager uses.
         * This is used for the remaining X509KeyManager methods:
         * {@link #getClientAliases(String, Principal[])},
         * {@link #getCertificateChain(String)},
         * {@link #getPrivateKey(String)} and
         * {@link #chooseClientAlias(String[], Principal[], Socket)}
         */
        private final JmeterKeyStore store;

        /**
         * Instantiate a new WrappedX509KeyManager.
         *
         * @param parent
         *            The parent X509KeyManager
         * @param ks
         *            The KeyStore we derive our client certs and keys from
         */
        public WrappedX509KeyManager(X509KeyManager parent, JmeterKeyStore ks) {
            this.manager = parent;
            this.store = ks;
        }

        /**
         * Compiles the list of all client aliases with a private key.
         *
         * @param keyType the key algorithm type name (RSA, DSA, etc.)
         * @param issuers  the CA certificates we are narrowing our selection on.
         *
         * @return the array of aliases; may be empty
         */
        @Override
        public String[] getClientAliases(String keyType, Principal[] issuers) {
            log.debug("WrappedX509Manager: getClientAliases: ");
            // implementation moved to JmeterKeystore as only that has the keyType info
            return this.store.getClientAliases(keyType, issuers);
        }

        /**
         * Get the list of server aliases for the SSLServerSockets. This is not
         * used in JMeter.
         *
         * @param keyType
         *            the type of private key the server expects (RSA, DSA,
         *            etc.)
         * @param issuers
         *            the CA certificates we are narrowing our selection on.
         * @return the ServerAliases value
         */
        @Override
        public String[] getServerAliases(String keyType, Principal[] issuers) {
            log.debug("WrappedX509Manager: getServerAliases: ");
            return this.manager.getServerAliases(keyType, issuers);
        }

        /**
         * Get the Certificate chain for a particular alias
         *
         * @param alias
         *            The client alias
         * @return The CertificateChain value
         */
        @Override
        public X509Certificate[] getCertificateChain(String alias) {
            log.debug("WrappedX509Manager: getCertificateChain(" + alias + ")");
            return this.store.getCertificateChain(alias);
        }

        /**
         * Get the Private Key for a particular alias
         *
         * @param alias
         *            The client alias
         * @return The PrivateKey value
         */
        @Override
        public PrivateKey getPrivateKey(String alias) {
            PrivateKey privateKey = this.store.getPrivateKey(alias);
            log.debug("WrappedX509Manager: getPrivateKey: " + privateKey);
            return privateKey;
        }

        /**
         * Select the Alias we will authenticate as if Client authentication is
         * required by the server we are connecting to. We get the list of
         * aliases, and if there is only one alias we automatically select it.
         * If there are more than one alias that has a private key, we prompt
         * the user to choose which alias using a combo box. Otherwise, we
         * simply provide a text box, which may or may not work. The alias does
         * have to match one in the keystore.
         *
         * TODO? - does not actually allow the user to choose an alias at present
         *
         * @param keyType the key algorithm type name(s), ordered with the most-preferred key type first.
         * @param issuers the list of acceptable CA issuer subject names or null if it does not matter which issuers are used.
         * @param socket the socket to be used for this connection.
         *     This parameter can be null, which indicates that implementations are free to select an alias applicable to any socket.
         *
         * @see javax.net.ssl.X509KeyManager#chooseClientAlias(String[], Principal[], Socket)
         */
        @Override
        public String chooseClientAlias(String[] keyType, Principal[] issuers, Socket socket) {
            log.debug("keyType: " + keyType[0]);
            String alias = this.store.getAlias();
            if (alias == null || alias.length() == 0) {
                log.debug("ClientAlias not found.");
            }
            return alias;
        }

        /**
         * Choose the server alias for the SSLServerSockets. This are not used
         * in JMeter.
         *
         * @see javax.net.ssl.X509KeyManager#chooseServerAlias(String, Principal[], Socket)
         */
        @Override
        public String chooseServerAlias(String arg0, Principal[] arg1, Socket arg2) {
            return this.manager.chooseServerAlias(arg0, arg1, arg2);
        }
    }
}


text:
#ifndef __XBEE_MODE_MODE_H
#define __XBEE_MODE_MODE_H

struct xbee_modeData {
	struct xbee_serialInfo serialInfo; /* keep serialInfo first, otherwise xbee_xbeeRxIo() and xbee_xbeeTxIo() will break */
};

#endif /* __XBEE_MODE_MODE_H */


text:
/* c-arcmt-test.c */

#include "clang-c/Index.h"
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#if defined(_WIN32)
#include <io.h>
#include <fcntl.h>
#endif

static int print_remappings(const char *path) {
  CXRemapping remap;
  unsigned i, N;
  CXString origFname;
  CXString transFname;

  remap = clang_getRemappings(path);
  if (!remap)
    return 1;

  N = clang_remap_getNumFiles(remap);
  for (i = 0; i != N; ++i) {
    clang_remap_getFilenames(remap, i, &origFname, &transFname);

    fprintf(stdout, "%s\n", clang_getCString(origFname));
    fprintf(stdout, "%s\n", clang_getCString(transFname));

    clang_disposeString(origFname);
    clang_disposeString(transFname);
  }

  clang_remap_dispose(remap);
  return 0;
}

static int print_remappings_filelist(const char **files, unsigned numFiles) {
  CXRemapping remap;
  unsigned i, N;
  CXString origFname;
  CXString transFname;

  remap = clang_getRemappingsFromFileList(files, numFiles);
  if (!remap)
    return 1;

  N = clang_remap_getNumFiles(remap);
  for (i = 0; i != N; ++i) {
    clang_remap_getFilenames(remap, i, &origFname, &transFname);

    fprintf(stdout, "%s\n", clang_getCString(origFname));
    fprintf(stdout, "%s\n", clang_getCString(transFname));

    clang_disposeString(origFname);
    clang_disposeString(transFname);
  }

  clang_remap_dispose(remap);
  return 0;
}

/******************************************************************************/
/* Command line processing.                                                   */
/******************************************************************************/

static void print_usage(void) {
  fprintf(stderr,
    "usage: c-arcmt-test -mt-migrate-directory <path>\n"
    "       c-arcmt-test <remap-file-path1> <remap-file-path2> ...\n\n\n");
}

/***/

int carcmttest_main(int argc, const char **argv) {
  clang_enableStackTraces();
  if (argc == 3 && strncmp(argv[1], "-mt-migrate-directory", 21) == 0)
    return print_remappings(argv[2]);

  if (argc > 1)
    return print_remappings_filelist(argv+1, argc-1);

  print_usage();
  return 1;
}

/***/

/* We intentionally run in a separate thread to ensure we at least minimal
 * testing of a multithreaded environment (for example, having a reduced stack
 * size). */

typedef struct thread_info {
  int argc;
  const char **argv;
  int result;
} thread_info;
void thread_runner(void *client_data_v) {
  thread_info *client_data = client_data_v;
  client_data->result = carcmttest_main(client_data->argc, client_data->argv);
#ifdef __CYGWIN__
  fflush(stdout);  /* stdout is not flushed on Cygwin. */
#endif
}

int main(int argc, const char **argv) {
  thread_info client_data;

#if defined(_WIN32)
  if (getenv("LIBCLANG_LOGGING") == NULL)
    putenv("LIBCLANG_LOGGING=1");
  _setmode( _fileno(stdout), _O_BINARY );
#else
  setenv("LIBCLANG_LOGGING", "1", /*overwrite=*/0);
#endif

  if (getenv("CINDEXTEST_NOTHREADS"))
    return carcmttest_main(argc, argv);

  client_data.argc = argc;
  client_data.argv = argv;
  clang_executeOnThread(thread_runner, &client_data, 0);
  return client_data.result;
}


text:
package org.apache.cassandra.transport.frame.checksum;

import java.io.IOException;
import java.util.EnumSet;
import java.util.Random;

import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import org.apache.cassandra.config.DatabaseDescriptor;
import org.apache.cassandra.transport.Frame;
import org.apache.cassandra.transport.ProtocolException;
import org.apache.cassandra.transport.frame.compress.Compressor;
import org.apache.cassandra.transport.frame.compress.LZ4Compressor;
import org.apache.cassandra.transport.frame.compress.SnappyCompressor;
import org.apache.cassandra.utils.ChecksumType;
import org.apache.cassandra.utils.Pair;
import org.quicktheories.core.Gen;

import static org.quicktheories.QuickTheory.qt;
import static org.quicktheories.generators.SourceDSL.*;

public class ChecksummingTransformerTest
{
    private static final int DEFAULT_BLOCK_SIZE = 1 << 15;
    private static final int MAX_INPUT_SIZE = 1 << 18;
    private static final EnumSet<Frame.Header.Flag> FLAGS = EnumSet.of(Frame.Header.Flag.COMPRESSED, Frame.Header.Flag.CHECKSUMMED);

    @BeforeClass
    public static void init()
    {
        // required as static ChecksummingTransformer instances read default block size from config
        DatabaseDescriptor.clientInitialization();
    }

    @Test
    public void roundTripSafetyProperty()
    {
        qt().withExamples(500)
            .forAll(inputs(),
                    compressors(),
                    checksumTypes(),
                    blocksizes())
            .checkAssert(this::roundTrip);
    }

    @Test
    public void roundTripZeroLengthInput()
    {
        qt().withExamples(20)
            .forAll(zeroLengthInputs(),
                    compressors(),
                    checksumTypes(),
                    blocksizes())
            .checkAssert(this::roundTrip);
    }

    @Test
    public void corruptionCausesFailure()
    {
        qt().withExamples(500)
            .forAll(inputWithCorruptablePosition(),
                    integers().between(0, Byte.MAX_VALUE).map(Integer::byteValue),
                    compressors(),
                    checksumTypes())
            .checkAssert(this::roundTripWithCorruption);
    }

    private void roundTripWithCorruption(Pair<String, Integer> inputAndCorruptablePosition,
                                         byte corruptionValue,
                                         Compressor compressor,
                                         ChecksumType checksum)
    {
        String input = inputAndCorruptablePosition.left;
        ByteBuf expectedBuf = Unpooled.wrappedBuffer(input.getBytes());
        int byteToCorrupt = inputAndCorruptablePosition.right;
        ChecksummingTransformer transformer = new ChecksummingTransformer(checksum, DEFAULT_BLOCK_SIZE, compressor);
        ByteBuf outbound = transformer.transformOutbound(expectedBuf);

        // make sure we're actually expecting to produce some corruption
        if (outbound.getByte(byteToCorrupt) == corruptionValue)
            return;

        if (byteToCorrupt >= outbound.writerIndex())
            return;

        try
        {
            int oldIndex = outbound.writerIndex();
            outbound.writerIndex(byteToCorrupt);
            outbound.writeByte(corruptionValue);
            outbound.writerIndex(oldIndex);
            ByteBuf inbound = transformer.transformInbound(outbound, FLAGS);

            // verify that the content was actually corrupted
            expectedBuf.readerIndex(0);
            Assert.assertEquals(expectedBuf, inbound);
        } catch(ProtocolException e)
        {
            return;
        }

    }

    @Test
    public void roundTripWithSingleUncompressableChunk()
    {
        byte[] bytes = new byte[]{1};
        ChecksummingTransformer transformer = new ChecksummingTransformer(ChecksumType.CRC32, DEFAULT_BLOCK_SIZE, LZ4Compressor.INSTANCE);
        ByteBuf expectedBuf = Unpooled.wrappedBuffer(bytes);

        ByteBuf outbound = transformer.transformOutbound(expectedBuf);
        ByteBuf inbound = transformer.transformInbound(outbound, FLAGS);

        // reset reader index on expectedBuf back to 0 as it will have been entirely consumed by the transformOutbound() call
        expectedBuf.readerIndex(0);
        Assert.assertEquals(expectedBuf, inbound);
    }

    @Test
    public void roundTripWithCompressableAndUncompressableChunks() throws IOException
    {
        Compressor compressor = LZ4Compressor.INSTANCE;
        Random random = new Random();
        int inputLen = 127;

        byte[] uncompressable = new byte[inputLen];
        for (int i = 0; i < uncompressable.length; i++)
            uncompressable[i] = (byte) random.nextInt(127);

        byte[] compressed = new byte[compressor.maxCompressedLength(uncompressable.length)];
        Assert.assertTrue(compressor.compress(uncompressable, 0, uncompressable.length, compressed, 0) > uncompressable.length);

        byte[] compressable = new byte[inputLen];
        for (int i = 0; i < compressable.length; i++)
            compressable[i] = (byte)1;
        Assert.assertTrue(compressor.compress(compressable, 0, compressable.length, compressable, 0) < compressable.length);

        ChecksummingTransformer transformer = new ChecksummingTransformer(ChecksumType.CRC32, uncompressable.length, LZ4Compressor.INSTANCE);
        byte[] expectedBytes = new byte[inputLen * 3];
        ByteBuf expectedBuf = Unpooled.wrappedBuffer(expectedBytes);
        expectedBuf.writerIndex(0);
        expectedBuf.writeBytes(uncompressable);
        expectedBuf.writeBytes(uncompressable);
        expectedBuf.writeBytes(compressable);

        ByteBuf outbound = transformer.transformOutbound(expectedBuf);
        ByteBuf inbound = transformer.transformInbound(outbound, FLAGS);

        // reset reader index on expectedBuf back to 0 as it will have been entirely consumed by the transformOutbound() call
        expectedBuf.readerIndex(0);
        Assert.assertEquals(expectedBuf, inbound);
    }

    private void roundTrip(String input, Compressor compressor, ChecksumType checksum, int blockSize)
    {
        ChecksummingTransformer transformer = new ChecksummingTransformer(checksum, blockSize, compressor);
        byte[] expectedBytes = input.getBytes();
        ByteBuf expectedBuf = Unpooled.wrappedBuffer(expectedBytes);

        ByteBuf outbound = transformer.transformOutbound(expectedBuf);
        ByteBuf inbound = transformer.transformInbound(outbound, FLAGS);

        // reset reader index on expectedBuf back to 0 as it will have been entirely consumed by the transformOutbound() call
        expectedBuf.readerIndex(0);
        Assert.assertEquals(expectedBuf, inbound);
    }

    private Gen<Pair<String, Integer>> inputWithCorruptablePosition()
    {
        // we only generate corruption for byte 2 onward. This is to skip introducing corruption in the number
        // of chunks (which isn't checksummed
        return inputs().flatMap(s -> integers().between(2, s.length() + 2).map(i -> Pair.create(s, i)));
    }

    private Gen<String> inputs()
    {
        Gen<String> randomStrings = strings().basicMultilingualPlaneAlphabet().ofLengthBetween(0, MAX_INPUT_SIZE);
        Gen<String> highlyCompressable = strings().betweenCodePoints('c', 'e').ofLengthBetween(1, MAX_INPUT_SIZE);
        return randomStrings.mix(highlyCompressable, 50);
    }

    private Gen<String> zeroLengthInputs()
    {
        return strings().ascii().ofLength(0);
    }

    private Gen<Compressor> compressors()
    {
        return arbitrary().pick(null, LZ4Compressor.INSTANCE, SnappyCompressor.INSTANCE);
    }

    private Gen<ChecksumType> checksumTypes()
    {
        return arbitrary().enumValuesWithNoOrder(ChecksumType.class);
    }

    private Gen<Integer> blocksizes()
    {
        return arbitrary().constant(DEFAULT_BLOCK_SIZE);
    }

}


text:
"""
The main purpose of this module is to expose LinkCollector.collect_links().
"""

import cgi
import functools
import itertools
import logging
import mimetypes
import os
import re
from collections import OrderedDict

from pip._vendor import html5lib, requests
from pip._vendor.distlib.compat import unescape
from pip._vendor.requests.exceptions import RetryError, SSLError
from pip._vendor.six.moves.urllib import parse as urllib_parse
from pip._vendor.six.moves.urllib import request as urllib_request

from pip._internal.exceptions import NetworkConnectionError
from pip._internal.models.link import Link
from pip._internal.models.search_scope import SearchScope
from pip._internal.network.utils import raise_for_status
from pip._internal.utils.filetypes import ARCHIVE_EXTENSIONS
from pip._internal.utils.misc import pairwise, redact_auth_from_url
from pip._internal.utils.typing import MYPY_CHECK_RUNNING
from pip._internal.utils.urls import path_to_url, url_to_path
from pip._internal.vcs import is_url, vcs

if MYPY_CHECK_RUNNING:
    from optparse import Values
    from typing import (
        Callable, Iterable, List, MutableMapping, Optional,
        Protocol, Sequence, Tuple, TypeVar, Union,
    )
    import xml.etree.ElementTree

    from pip._vendor.requests import Response

    from pip._internal.network.session import PipSession

    HTMLElement = xml.etree.ElementTree.Element
    ResponseHeaders = MutableMapping[str, str]

    # Used in the @lru_cache polyfill.
    F = TypeVar('F')

    class LruCache(Protocol):
        def __call__(self, maxsize=None):
            # type: (Optional[int]) -> Callable[[F], F]
            raise NotImplementedError

logger = logging.getLogger(__name__)

# Fallback to noop_lru_cache in Python 2
# TODO: this can be removed when python 2 support is dropped!
def noop_lru_cache(maxsize=None):
    # type: (Optional[int]) -> Callable[[F], F]
    def _wrapper(f):
        # type: (F) -> F
        return f
    return _wrapper

_lru_cache = getattr(functools, "lru_cache", noop_lru_cache)  # type: LruCache

def _match_vcs_scheme(url):
    # type: (str) -> Optional[str]
    """Look for VCS schemes in the URL.

    Returns the matched VCS scheme, or None if there's no match.
    """
    for scheme in vcs.schemes:
        if url.lower().startswith(scheme) and url[len(scheme)] in '+:':
            return scheme
    return None

def _is_url_like_archive(url):
    # type: (str) -> bool
    """Return whether the URL looks like an archive.
    """
    filename = Link(url).filename
    for bad_ext in ARCHIVE_EXTENSIONS:
        if filename.endswith(bad_ext):
            return True
    return False

class _NotHTML(Exception):
    def __init__(self, content_type, request_desc):
        # type: (str, str) -> None
        super(_NotHTML, self).__init__(content_type, request_desc)
        self.content_type = content_type
        self.request_desc = request_desc

def _ensure_html_header(response):
    # type: (Response) -> None
    """Check the Content-Type header to ensure the response contains HTML.

    Raises `_NotHTML` if the content type is not text/html.
    """
    content_type = response.headers.get("Content-Type", "")
    if not content_type.lower().startswith("text/html"):
        raise _NotHTML(content_type, response.request.method)

class _NotHTTP(Exception):
    pass

def _ensure_html_response(url, session):
    # type: (str, PipSession) -> None
    """Send a HEAD request to the URL, and ensure the response contains HTML.

    Raises `_NotHTTP` if the URL is not available for a HEAD request, or
    `_NotHTML` if the content type is not text/html.
    """
    scheme, netloc, path, query, fragment = urllib_parse.urlsplit(url)
    if scheme not in {'http', 'https'}:
        raise _NotHTTP()

    resp = session.head(url, allow_redirects=True)
    raise_for_status(resp)

    _ensure_html_header(resp)

def _get_html_response(url, session):
    # type: (str, PipSession) -> Response
    """Access an HTML page with GET, and return the response.

    This consists of three parts:

    1. If the URL looks suspiciously like an archive, send a HEAD first to
       check the Content-Type is HTML, to avoid downloading a large file.
       Raise `_NotHTTP` if the content type cannot be determined, or
       `_NotHTML` if it is not HTML.
    2. Actually perform the request. Raise HTTP exceptions on network failures.
    3. Check the Content-Type header to make sure we got HTML, and raise
       `_NotHTML` otherwise.
    """
    if _is_url_like_archive(url):
        _ensure_html_response(url, session=session)

    logger.debug('Getting page %s', redact_auth_from_url(url))

    resp = session.get(
        url,
        headers={
            "Accept": "text/html",
            # We don't want to blindly returned cached data for
            # /simple/, because authors generally expecting that
            # twine upload && pip install will function, but if
            # they've done a pip install in the last ~10 minutes
            # it won't. Thus by setting this to zero we will not
            # blindly use any cached data, however the benefit of
            # using max-age=0 instead of no-cache, is that we will
            # still support conditional requests, so we will still
            # minimize traffic sent in cases where the page hasn't
            # changed at all, we will just always incur the round
            # trip for the conditional GET now instead of only
            # once per 10 minutes.
            # For more information, please see pypa/pip#5670.
            "Cache-Control": "max-age=0",
        },
    )
    raise_for_status(resp)

    # The check for archives above only works if the url ends with
    # something that looks like an archive. However that is not a
    # requirement of an url. Unless we issue a HEAD request on every
    # url we cannot know ahead of time for sure if something is HTML
    # or not. However we can check after we've downloaded it.
    _ensure_html_header(resp)

    return resp

def _get_encoding_from_headers(headers):
    # type: (ResponseHeaders) -> Optional[str]
    """Determine if we have any encoding information in our headers.
    """
    if headers and "Content-Type" in headers:
        content_type, params = cgi.parse_header(headers["Content-Type"])
        if "charset" in params:
            return params['charset']
    return None

def _determine_base_url(document, page_url):
    # type: (HTMLElement, str) -> str
    """Determine the HTML document's base URL.

    This looks for a ``<base>`` tag in the HTML document. If present, its href
    attribute denotes the base URL of anchor tags in the document. If there is
    no such tag (or if it does not have a valid href attribute), the HTML
    file's URL is used as the base URL.

    :param document: An HTML document representation. The current
        implementation expects the result of ``html5lib.parse()``.
    :param page_url: The URL of the HTML document.
    """
    for base in document.findall(".//base"):
        href = base.get("href")
        if href is not None:
            return href
    return page_url

def _clean_url_path_part(part):
    # type: (str) -> str
    """
    Clean a "part" of a URL path (i.e. after splitting on "@" characters).
    """
    # We unquote prior to quoting to make sure nothing is double quoted.
    return urllib_parse.quote(urllib_parse.unquote(part))

def _clean_file_url_path(part):
    # type: (str) -> str
    """
    Clean the first part of a URL path that corresponds to a local
    filesystem path (i.e. the first part after splitting on "@" characters).
    """
    # We unquote prior to quoting to make sure nothing is double quoted.
    # Also, on Windows the path part might contain a drive letter which
    # should not be quoted. On Linux where drive letters do not
    # exist, the colon should be quoted. We rely on urllib.request
    # to do the right thing here.
    return urllib_request.pathname2url(urllib_request.url2pathname(part))

# percent-encoded:                   /
_reserved_chars_re = re.compile('(@|%2F)', re.IGNORECASE)

def _clean_url_path(path, is_local_path):
    # type: (str, bool) -> str
    """
    Clean the path portion of a URL.
    """
    if is_local_path:
        clean_func = _clean_file_url_path
    else:
        clean_func = _clean_url_path_part

    # Split on the reserved characters prior to cleaning so that
    # revision strings in VCS URLs are properly preserved.
    parts = _reserved_chars_re.split(path)

    cleaned_parts = []
    for to_clean, reserved in pairwise(itertools.chain(parts, [''])):
        cleaned_parts.append(clean_func(to_clean))
        # Normalize %xx escapes (e.g. %2f -> %2F)
        cleaned_parts.append(reserved.upper())

    return ''.join(cleaned_parts)

def _clean_link(url):
    # type: (str) -> str
    """
    Make sure a link is fully quoted.
    For example, if ' ' occurs in the URL, it will be replaced with "%20",
    and without double-quoting other characters.
    """
    # Split the URL into parts according to the general structure
    # `scheme://netloc/path;parameters?query#fragment`.
    result = urllib_parse.urlparse(url)
    # If the netloc is empty, then the URL refers to a local filesystem path.
    is_local_path = not result.netloc
    path = _clean_url_path(result.path, is_local_path=is_local_path)
    return urllib_parse.urlunparse(result._replace(path=path))

def _create_link_from_element(
    anchor,    # type: HTMLElement
    page_url,  # type: str
    base_url,  # type: str
):
    # type: (...) -> Optional[Link]
    """
    Convert an anchor element in a simple repository page to a Link.
    """
    href = anchor.get("href")
    if not href:
        return None

    url = _clean_link(urllib_parse.urljoin(base_url, href))
    pyrequire = anchor.get('data-requires-python')
    pyrequire = unescape(pyrequire) if pyrequire else None

    yanked_reason = anchor.get('data-yanked')
    if yanked_reason:
        # This is a unicode string in Python 2 (and 3).
        yanked_reason = unescape(yanked_reason)

    link = Link(
        url,
        comes_from=page_url,
        requires_python=pyrequire,
        yanked_reason=yanked_reason,
    )

    return link

class CacheablePageContent(object):
    def __init__(self, page):
        # type: (HTMLPage) -> None
        assert page.cache_link_parsing
        self.page = page

    def __eq__(self, other):
        # type: (object) -> bool
        return (isinstance(other, type(self)) and
                self.page.url == other.page.url)

    def __hash__(self):
        # type: () -> int
        return hash(self.page.url)

def with_cached_html_pages(
    fn,    # type: Callable[[HTMLPage], Iterable[Link]]
):
    # type: (...) -> Callable[[HTMLPage], List[Link]]
    """
    Given a function that parses an Iterable[Link] from an HTMLPage, cache the
    function's result (keyed by CacheablePageContent), unless the HTMLPage
    `page` has `page.cache_link_parsing == False`.
    """

    @_lru_cache(maxsize=None)
    def wrapper(cacheable_page):
        # type: (CacheablePageContent) -> List[Link]
        return list(fn(cacheable_page.page))

    @functools.wraps(fn)
    def wrapper_wrapper(page):
        # type: (HTMLPage) -> List[Link]
        if page.cache_link_parsing:
            return wrapper(CacheablePageContent(page))
        return list(fn(page))

    return wrapper_wrapper

@with_cached_html_pages
def parse_links(page):
    # type: (HTMLPage) -> Iterable[Link]
    """
    Parse an HTML document, and yield its anchor elements as Link objects.
    """
    document = html5lib.parse(
        page.content,
        transport_encoding=page.encoding,
        namespaceHTMLElements=False,
    )

    url = page.url
    base_url = _determine_base_url(document, url)
    for anchor in document.findall(".//a"):
        link = _create_link_from_element(
            anchor,
            page_url=url,
            base_url=base_url,
        )
        if link is None:
            continue
        yield link

class HTMLPage(object):
    """Represents one page, along with its URL"""

    def __init__(
        self,
        content,                  # type: bytes
        encoding,                 # type: Optional[str]
        url,                      # type: str
        cache_link_parsing=True,  # type: bool
    ):
        # type: (...) -> None
        """
        :param encoding: the encoding to decode the given content.
        :param url: the URL from which the HTML was downloaded.
        :param cache_link_parsing: whether links parsed from this page's url
                                   should be cached. PyPI index urls should
                                   have this set to False, for example.
        """
        self.content = content
        self.encoding = encoding
        self.url = url
        self.cache_link_parsing = cache_link_parsing

    def __str__(self):
        # type: () -> str
        return redact_auth_from_url(self.url)

def _handle_get_page_fail(
    link,  # type: Link
    reason,  # type: Union[str, Exception]
    meth=None  # type: Optional[Callable[..., None]]
):
    # type: (...) -> None
    if meth is None:
        meth = logger.debug
    meth("Could not fetch URL %s: %s - skipping", link, reason)

def _make_html_page(response, cache_link_parsing=True):
    # type: (Response, bool) -> HTMLPage
    encoding = _get_encoding_from_headers(response.headers)
    return HTMLPage(
        response.content,
        encoding=encoding,
        url=response.url,
        cache_link_parsing=cache_link_parsing)

def _get_html_page(link, session=None):
    # type: (Link, Optional[PipSession]) -> Optional[HTMLPage]
    if session is None:
        raise TypeError(
            "_get_html_page() missing 1 required keyword argument: 'session'"
        )

    url = link.url.split('#', 1)[0]

    # Check for VCS schemes that do not support lookup as web pages.
    vcs_scheme = _match_vcs_scheme(url)
    if vcs_scheme:
        logger.warning('Cannot look at %s URL %s because it does not support '
                       'lookup as web pages.', vcs_scheme, link)
        return None

    # Tack index.html onto file:// URLs that point to directories
    scheme, _, path, _, _, _ = urllib_parse.urlparse(url)
    if (scheme == 'file' and os.path.isdir(urllib_request.url2pathname(path))):
        # add trailing slash if not present so urljoin doesn't trim
        # final segment
        if not url.endswith('/'):
            url += '/'
        url = urllib_parse.urljoin(url, 'index.html')
        logger.debug(' file: URL is directory, getting %s', url)

    try:
        resp = _get_html_response(url, session=session)
    except _NotHTTP:
        logger.warning(
            'Skipping page %s because it looks like an archive, and cannot '
            'be checked by a HTTP HEAD request.', link,
        )
    except _NotHTML as exc:
        logger.warning(
            'Skipping page %s because the %s request got Content-Type: %s.'
            'The only supported Content-Type is text/html',
            link, exc.request_desc, exc.content_type,
        )
    except NetworkConnectionError as exc:
        _handle_get_page_fail(link, exc)
    except RetryError as exc:
        _handle_get_page_fail(link, exc)
    except SSLError as exc:
        reason = "There was a problem confirming the ssl certificate: "
        reason += str(exc)
        _handle_get_page_fail(link, reason, meth=logger.info)
    except requests.ConnectionError as exc:
        _handle_get_page_fail(link, "connection error: {}".format(exc))
    except requests.Timeout:
        _handle_get_page_fail(link, "timed out")
    else:
        return _make_html_page(resp,
                               cache_link_parsing=link.cache_link_parsing)
    return None

def _remove_duplicate_links(links):
    # type: (Iterable[Link]) -> List[Link]
    """
    Return a list of links, with duplicates removed and ordering preserved.
    """
    # We preserve the ordering when removing duplicates because we can.
    return list(OrderedDict.fromkeys(links))

def group_locations(locations, expand_dir=False):
    # type: (Sequence[str], bool) -> Tuple[List[str], List[str]]
    """
    Divide a list of locations into two groups: "files" (archives) and "urls."

    :return: A pair of lists (files, urls).
    """
    files = []
    urls = []

    # puts the url for the given file path into the appropriate list
    def sort_path(path):
        # type: (str) -> None
        url = path_to_url(path)
        if mimetypes.guess_type(url, strict=False)[0] == 'text/html':
            urls.append(url)
        else:
            files.append(url)

    for url in locations:

        is_local_path = os.path.exists(url)
        is_file_url = url.startswith('file:')

        if is_local_path or is_file_url:
            if is_local_path:
                path = url
            else:
                path = url_to_path(url)
            if os.path.isdir(path):
                if expand_dir:
                    path = os.path.realpath(path)
                    for item in os.listdir(path):
                        sort_path(os.path.join(path, item))
                elif is_file_url:
                    urls.append(url)
                else:
                    logger.warning(
                        "Path '%s' is ignored: it is a directory.", path,
                    )
            elif os.path.isfile(path):
                sort_path(path)
            else:
                logger.warning(
                    "Url '%s' is ignored: it is neither a file "
                    "nor a directory.", url,
                )
        elif is_url(url):
            # Only add url with clear scheme
            urls.append(url)
        else:
            logger.warning(
                "Url '%s' is ignored. It is either a non-existing "
                "path or lacks a specific scheme.", url,
            )

    return files, urls

class CollectedLinks(object):

    """
    Encapsulates the return value of a call to LinkCollector.collect_links().

    The return value includes both URLs to project pages containing package
    links, as well as individual package Link objects collected from other
    sources.

    This info is stored separately as:

    (1) links from the configured file locations,
    (2) links from the configured find_links, and
    (3) urls to HTML project pages, as described by the PEP 503 simple
        repository API.
    """

    def __init__(
        self,
        files,         # type: List[Link]
        find_links,    # type: List[Link]
        project_urls,  # type: List[Link]
    ):
        # type: (...) -> None
        """
        :param files: Links from file locations.
        :param find_links: Links from find_links.
        :param project_urls: URLs to HTML project pages, as described by
            the PEP 503 simple repository API.
        """
        self.files = files
        self.find_links = find_links
        self.project_urls = project_urls

class LinkCollector(object):

    """
    Responsible for collecting Link objects from all configured locations,
    making network requests as needed.

    The class's main method is its collect_links() method.
    """

    def __init__(
        self,
        session,       # type: PipSession
        search_scope,  # type: SearchScope
    ):
        # type: (...) -> None
        self.search_scope = search_scope
        self.session = session

    @classmethod
    def create(cls, session, options, suppress_no_index=False):
        # type: (PipSession, Values, bool) -> LinkCollector
        """
        :param session: The Session to use to make requests.
        :param suppress_no_index: Whether to ignore the --no-index option
            when constructing the SearchScope object.
        """
        index_urls = [options.index_url] + options.extra_index_urls
        if options.no_index and not suppress_no_index:
            logger.debug(
                'Ignoring indexes: %s',
                ','.join(redact_auth_from_url(url) for url in index_urls),
            )
            index_urls = []

        # Make sure find_links is a list before passing to create().
        find_links = options.find_links or []

        search_scope = SearchScope.create(
            find_links=find_links, index_urls=index_urls,
        )
        link_collector = LinkCollector(
            session=session, search_scope=search_scope,
        )
        return link_collector

    @property
    def find_links(self):
        # type: () -> List[str]
        return self.search_scope.find_links

    def fetch_page(self, location):
        # type: (Link) -> Optional[HTMLPage]
        """
        Fetch an HTML page containing package links.
        """
        return _get_html_page(location, session=self.session)

    def collect_links(self, project_name):
        # type: (str) -> CollectedLinks
        """Find all available links for the given project name.

        :return: All the Link objects (unfiltered), as a CollectedLinks object.
        """
        search_scope = self.search_scope
        index_locations = search_scope.get_index_urls_locations(project_name)
        index_file_loc, index_url_loc = group_locations(index_locations)
        fl_file_loc, fl_url_loc = group_locations(
            self.find_links, expand_dir=True,
        )

        file_links = [
            Link(url) for url in itertools.chain(index_file_loc, fl_file_loc)
        ]

        # We trust every directly linked archive in find_links
        find_link_links = [Link(url, '-f') for url in self.find_links]

        # We trust every url that the user has given us whether it was given
        # via --index-url or --find-links.
        # We want to filter out anything that does not have a secure origin.
        url_locations = [
            link for link in itertools.chain(
                # Mark PyPI indices as "cache_link_parsing == False" -- this
                # will avoid caching the result of parsing the page for links.
                (Link(url, cache_link_parsing=False) for url in index_url_loc),
                (Link(url) for url in fl_url_loc),
            )
            if self.session.is_secure_origin(link)
        ]

        url_locations = _remove_duplicate_links(url_locations)
        lines = [
            '{} location(s) to search for versions of {}:'.format(
                len(url_locations), project_name,
            ),
        ]
        for link in url_locations:
            lines.append('* {}'.format(link))
        logger.debug('\n'.join(lines))

        return CollectedLinks(
            files=file_links,
            find_links=find_link_links,
            project_urls=url_locations,
        )


text:
typedef struct T *T;

extern T Seq_new(int hint);

extern T Seq_seq(void *x, ...);

extern void Seq_free(T *seq);

extern int Seq_length(T seq);

extern void *Seq_get(T seq, int i);

extern void *Seq_put(T seq, int i, void *x);

extern void *Seq_addlo(T seq, void *x);

extern void *Seq_addhi(T seq, void *x);

extern void *Seq_remlo(T seq);

extern void *Seq_remhi(T seq);

#undef T

#endif


text:
/* eslint quotes: 0 */
'use strict';

const vio = require('../../core/vio');
const refactor = require('../../core/refactor/cls');
const helpers = require('../helpers');

const expectLines = helpers.expectLines;
const V_FILE = 'vio-temp-file.js';

describe('renameClassName', function() {
  before(() => {
    vio.reset();
  });
  const CODE = `\
import React, { PureComponent } from 'react';

export class Hello extends PureComponent {
  render() {
    return (
      <h1 className="home-hello">
       Welcome to your Rekit project!
      </h1>
    );
  }
}

export default Hello;
`;
  it('rename es6 class name', () => {
    vio.put(V_FILE, CODE);
    refactor.renameClassName(V_FILE, 'Hello', 'NewHello');
    expectLines(V_FILE, [
      'export class NewHello extends PureComponent {',
      'export default NewHello;',
    ]);
  });
});


text:
require "faraday"
require "faraday_middleware"
require "active_model_serializers"

require_relative "ssl_reminder/engine"
require_relative "ssl_reminder/certificates/connection"
require_relative "ssl_reminder/certificates/scanner"
require_relative "ssl_reminder/certificates/notifier"

module SslReminder
end


text:
import json
import urllib.request
from urllib.error import HTTPError
from retry import retry
from django.contrib.gis.geos import GEOSGeometry
from storage.shapefile import convert_geom_to_multipolygon

class OsniLayer:
    @retry(HTTPError, tries=2, delay=30)
    def get_data_from_url(self, url):
        with urllib.request.urlopen(url, timeout=30) as response:
            """
            When an ArcGIS server can't generate a response
            within X amount of time, it will return a 202 ACCEPTED
            response with a body like
            {
              "processingTime": "27.018 seconds",
              "status": "Processing",
              "generating": {}
            }
            and expects the client to poll it.
            """
            if response.code == 202:
                raise HTTPError(
                    url, response.code, response.msg, response.headers, response.fp
                )
            data = response.read()
            return data

    def __init__(self, url, gss_field, name_field):
        ds = json.loads(self.get_data_from_url(url).decode("utf-8"))
        self.features = []

        for feature in ds["features"]:
            geom = GEOSGeometry(json.dumps(feature["geometry"]), srid=4326)
            geom = convert_geom_to_multipolygon(geom)
            rec = {
                "geometry": geom,
                "name": feature["properties"][name_field],
                "OBJECTID": feature["properties"]["OBJECTID"],
            }
            if gss_field:
                rec["gss"] = feature["properties"][gss_field]
            self.features.append(rec)


text:
<!DOCTYPE html>

	<meta charset="utf-8">

	<title>Class Xvolutions\AdminBundle\Tests\Controller\AdminControllerTest</title>

	<link rel="stylesheet" href="resources/style.css?e99947befd7bf673c6b43ff75e9e0f170c88a60e">

		Overview

Namespaces

						Xvolutions

						AdminBundle

						Command

						Controller

						Admin

						DependencyInjection

						Entity

						Form

						Helpers

						Tests

						Controller

						Admin

						Entity

						Helpers

						Selenium

						Tests

Classes

AdminControllerTest

	<form id="search">
		<input type="hidden" name="cx" value="">
		<input type="hidden" name="ie" value="UTF-8">
		<input type="text" name="q" class="text" placeholder="Search">
	</form>

				Overview

				Namespace

Class

Class AdminControllerTest

Description of AdminControllerTest

Symfony\Bundle\FrameworkBundle\Test\WebTestCase

Xvolutions\AdminBundle\Tests\Controller\AdminControllerTest

		Namespace: Xvolutions\AdminBundle\Tests\Controller

				Author:
				Pedro Resende pedroresende@mail.resende.biz

			Located at AdminBundle/Tests/Controller/AdminControllerTest.php

Methods summary

			 public

		#
		setUp( )

			 public

		#
		testFailBackoffice( )

			 public

		#
		testBackoffice( )

			 public

		#
		testSetup( )

			 public

		#
		testPhpinfo( )

		 API documentation generated by ApiGen


text:
package_files=$( /usr/bin/find  | grep -E ".sty|.tex|.md" )
echo "Compiling manual"
cd manual
texify --pdf --quiet spectralsequencesmanual.tex
#latexmk -pdf -silent spectralsequencesmanual.tex
if [ $? -ne 0 ] ; then
    echo "Manual failed, quitting."
    exit 1
fi
cd ..

echo "Compiling examples"
./compileexamples.sh | tee timetest.txt
if [ ${PIPESTATUS[0]} -gt 0 ] ; then
    echo "Examples failed; quitting."
    exit 1
fi
sed -r --in-place "s/\x1B\[([0-9]{1,3}((;[0-9]{1,3})*)?)?[m|K]//g" timetest.txt

echo "Cleanup tex output files"
/usr/bin/find -regextype egrep -regex ".*\.aux|.*\.bbl|.*\.dvi|.*\.log|.*\.synctex.*|.*\.toc|.*\.out|.*\.up.*" -delete

# If a version number was supplied, replace versions and date strings:
if [ "$1" ] ; then
    echo "Replacing date strings and version numbers"
    echo $package_files | xargs sed --in-place "s/Date: ....-..-../Date: $(date +%Y-%m-%d)/g"
    sed --in-place "s_ProvidesPackage{spectralsequences}\[.*\]_ProvidesPackage{spectralsequences}[$(date +%Y/%m/%d) v$1]_g" spectralsequences.sty
    sed --in-place "s_version{.*}_version{Version $1}_g" manual/spectralsequencesmanual.tex
    echo $package_files | xargs sed -E --in-place "s/spectralsequences v[0-9]*\.[0-9]*\.[0-9]*[[:punct:]]?[a-z]*/spectralsequences v$1/g"
fi

echo "Zipping files"
cd ..
powershell "Get-ChildItem -r -Path spectralsequences -Include '*.sty','*.tex','*.md','*.pdf'  | Write-Zip -OutputPath spectralsequences.zip | Out-Null"
mv spectralsequences.zip spectralsequences
cd spectralsequences

if [ -s commitmessage.txt ] ; then
    echo "Applying dos2unix"
    echo $package_files | xargs dos2unix --quiet

    echo "Committing"
    git commit -a --file commitmessage.txt
    mv commitmessage.txt commitmessage.bak.txt
    printf "" > commitmessage.txt
    echo "Pushing commit"
    git push
fi

if [ "$1" ] ; then
    while true; do
        read -p $'Do you wish commit the package to CTAN?\n' yn
        case $yn in
            [Yy]es ) ./ctan-upload.sh ./ctan-upload-fields.def $1; break;;
            [Nn]* ) break;;
            * ) echo "Please answer yes or no.";;
        esac
    done
fi


text:
<?php

namespace NTLAB\JS\Script\Bootstrap\Dialog;

use NTLAB\JS\Script\JQuery as Base;
use NTLAB\JS\Repository;

/**
 * Bootstrap message modal.
 *
 * Usage:
 * $.ntdlg.message('my', 'Message', 'This is an example');
 *
 * @author Toha
 */
class Message extends Base
{
    protected function configure()
    {
        $this->addDependencies('JQuery.NS', 'Bootstrap.Dialog');
        $this->setPosition(Repository::POSITION_FIRST);
    }

    public function getScript()
    {
        $ok = $this->trans('OK');

        return <<<EOF
$.define('ntdlg', {
    message: function(id, title, message, icon) {
        $.ntdlg.dialog(id, title, message, icon, {
            '$ok': {
                icon: $.ntdlg.BTN_ICON_OK,
                handler: function() {
                    $.ntdlg.close($(this));
                }
            }
        });
    }
}, true);
EOF;
    }
}


text:
var mongoose = require('mongoose');

// TODO: https://github.com/digitarald/d2g/issues/34
var signedPackageSchema = new mongoose.Schema({
    signedPackage: Buffer
});

module.exports = mongoose.model('SignedPackage', signedPackageSchema);


text:
import {
  AIRPORTS_LOAD, AIRPORTS_UNLOAD, AIRPORT_LOAD, AIRPORT_UNLOAD
} from '../actions';
import {
  watchAirports, unwatchAirports, watchAirport, unwatchAirport
} from '../api/airports';

const headers = {
  Accept: 'application/json',
  'Content-Type': 'application/json',
};

function processStatus(response) {
  if (response.ok) {
    return Promise.resolve(response);
  }
  return Promise.reject(response.statusText || `Error ${response.status}`);
}

export function addAirport(airport) {
  return () => {
    const data = JSON.stringify(airport);
    const options = { method: 'POST', headers, body: data };
    return fetch('/api/airport', options)
      .then(processStatus)
      .then(response => response.json());
  };
}

export function loadAirports() {
  return dispatch => (
    watchAirports()
      .on('success',
        payload => dispatch({ type: AIRPORTS_LOAD, payload })
      )
      .on('error',
        payload => dispatch({ type: AIRPORTS_LOAD, error: true, payload })
      )
      .start()
  );
}

export function unloadAirports() {
  unwatchAirports();
  return { type: AIRPORTS_UNLOAD };
}

export function loadAirport(id) {
  return dispatch => (
    watchAirport(id)
      .on('success',
        payload => dispatch({ type: AIRPORT_LOAD, payload })
      )
      .on('error',
        payload => dispatch({ type: AIRPORT_LOAD, error: true, payload })
      )
      .start()
  );
}

export function unloadAirport(id) {
  unwatchAirport(id);
  return { type: AIRPORT_UNLOAD };
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Jl S. Afr. Bot. 128 (1970)

#### Original name
Xylaria ciliata Pat.

### Remarks
null