text:
<?xml version="1.0" encoding="UTF-8"?>
<!-- Licensed to the Apache Software Foundation (ASF) under one or more contributor
license agreements. See the NOTICE file distributed with this work for additional
information regarding copyright ownership. The ASF licenses this file to
You 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. -->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <artifactId>htrace-hbase</artifactId>
  <packaging>jar</packaging>

  <parent>
    <artifactId>htrace</artifactId>
    <groupId>org.htrace</groupId>
    <version>3.0.4</version>
  </parent>

  <name>htrace-hbase</name>
  <description>
    htrace-hbase is the tools to send tracing information
    to a HBase database for analysis later.
  </description>
  <url>https://github.com/cloudera/htrace</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <hbase.version>2.0.0-SNAPSHOT</hbase.version>
    <!-- <hbase.version>0.99.0-SNAPSHOT</hbase.version> -->
    <hadoop.version>2.4.0</hadoop.version>
    <!-- <hadoop.version>3.0.0-SNAPSHOT</hadoop.version> -->
    <protobuf.version>2.5.0</protobuf.version>
  </properties>

  <build>
    <resources>
      <resource>
        <directory>${basedir}/src/main</directory>
        <includes>
          <include>webapps/**</include>
        </includes>
      </resource>
    </resources>
    <plugins>
      <plugin>
        <groupId>org.apache.rat</groupId>
        <artifactId>apache-rat-plugin</artifactId>
        <configuration>
          <excludes>
            <exclude>**/generated/**</exclude>
            <exclude>**/webapps/static/d3.min.js</exclude>
          </excludes>
        </configuration>
      </plugin>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-source-plugin</artifactId>
      </plugin>
      <plugin>
        <artifactId>maven-assembly-plugin</artifactId>
        <configuration>
          <descriptorRefs>
            <descriptorRef>jar-with-dependencies</descriptorRef>
          </descriptorRefs>
        </configuration>
      </plugin>
      <plugin>
        <artifactId>maven-compiler-plugin</artifactId>
      </plugin>
      <plugin>
        <artifactId>maven-javadoc-plugin</artifactId>
      </plugin>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-gpg-plugin</artifactId>
      </plugin>
      <plugin>
        <!-- explicitly define maven-deploy-plugin after other to force exec order -->
        <artifactId>maven-deploy-plugin</artifactId>
      </plugin>
    </plugins>
  </build>

  <dependencies>
    <!-- Module deps. -->
    <dependency>
      <groupId>org.htrace</groupId>
      <artifactId>htrace-core</artifactId>
      <version>${project.version}</version>
      <scope>provided</scope>
    </dependency>
    <dependency>
      <groupId>org.htrace</groupId>
      <artifactId>htrace-core</artifactId>
      <version>${project.version}</version>
      <classifier>tests</classifier>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>com.google.protobuf</groupId>
      <artifactId>protobuf-java</artifactId>
      <version>${protobuf.version}</version>
      <scope>provided</scope>
    </dependency>
    <!-- Global deps. -->
    <dependency>
      <groupId>commons-logging</groupId>
      <artifactId>commons-logging</artifactId>
      <scope>provided</scope>
    </dependency>
    <dependency>
      <groupId>com.google.guava</groupId>
      <artifactId>guava</artifactId>
      <scope>provided</scope>
    </dependency>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <scope>test</scope>
    </dependency>
    <!-- HBase specific deps. -->
    <dependency>
      <groupId>org.apache.hbase</groupId>
      <artifactId>hbase-client</artifactId>
      <version>${hbase.version}</version>
      <exclusions>
        <exclusion>
          <groupId>org.htrace</groupId>
          <artifactId>htrace-core</artifactId>
        </exclusion>
      </exclusions>
    </dependency>
    <dependency>
      <groupId>org.apache.hbase</groupId>
      <artifactId>hbase-testing-util</artifactId>
      <version>${hbase.version}</version>
      <scope>test</scope>
    </dependency>
  </dependencies>

  <profiles>
    <profile>
      <id>compile-protobuf</id>
      <activation>
        <property>
          <name>compile-protobuf</name>
        </property>
      </activation>
      <build>
        <plugins>
          <plugin>
            <groupId>org.apache.hadoop</groupId>
            <artifactId>hadoop-maven-plugins</artifactId>
            <version>${hadoop.version}</version>
            <configuration>
              <protocVersion>${protobuf.version}</protocVersion>
              <protocCommand>${protoc.path}</protocCommand>
            </configuration>
            <executions>
              <execution>
                <id>compile-protoc</id>
                <phase>generate-sources</phase>
                <goals>
                  <goal>protoc</goal>
                </goals>
                <configuration>
                  <imports>
                    <param>${basedir}/src/main/protobuf</param>
                  </imports>
                  <source>
                    <directory>${basedir}/src/main/protobuf</directory>
                    <includes>
                      <include>Span.proto</include>
                    </includes>
                  </source>
                  <output>${basedir}/src/main/java/</output>
                </configuration>
              </execution>
            </executions>
          </plugin>
        </plugins>
      </build>
    </profile>
  </profiles>

</project>


text:
<?php

namespace app\modules\ecom\controllers;

use Yii;
use app\modules\ecom\models\Account;
use app\modules\ecom\models\search\AccountSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use app\modules\ecom\models\forms\CreateAccountForm;

/**
 * AccountsController implements the CRUD actions for Account model.
 */
class AccountsController extends Controller
{
    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            'access' => [
                'class' => \yii\filters\AccessControl::className(),
                'rules' => [
                    [
                        'allow' => true,
                        'actions' => ['index'],
                        'roles' => ['ecom.accounts.index'],
                    ],
                    [
                        'allow' => true,
                        'actions' => ['create'],
                        'roles' => ['ecom.accounts.create'],
                    ],

                    [
                        'allow' => true,
                        'actions' => ['view'],
                        'roles' => ['ecom.accounts.view'],
                    ],
                    [
                        'allow' => true,
                        'actions' => ['details'],
                        'roles' => ['ecom.accounts.details'],
                    ],
                    [
                        'allow' => true,
                        'actions' => ['update'],
                        'roles' => ['ecom.accounts.update'],
                    ],
                    [
                        'allow' => true,
                        'actions' => ['delete'],
                        'roles' => ['ecom.accounts.delete'],
                    ],
                    [
                        'allow' => true,
                        'actions' => ['list'],
                        'roles' => ['ecom.accounts.list'],
                    ],
                ],
            ],
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['POST'],
                ],
            ],
        ];
    }

    /**
     * Index action
     * @return mixed
     */
    public function actionIndex()
    {
        return $this->render('index');
    }

    /**
     * Displays a single Account model.
     * @param integer $id
     * @return mixed
     */
    public function actionDetails($id)
    {
        return $this->render('details', [
            'model' => $this->findModel($id),
        ]);
    }

    /**
     * Displays a single Account model.
     * @param integer $id
     * @return mixed
     */
    public function actionView($id)
    {
        return $this->render('view', [
            'model' => $this->findModel($id),
        ]);
    }

    /**
     * Creates a new Account model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $model = new CreateAccountForm();

        if ($model->load(Yii::$app->request->post()) && $model->create()) {
            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            return $this->render('create', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Updates an existing Account model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id
     * @return mixed
     */
    public function actionUpdate($id)
    {
        $model = $this->findModel($id);

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            return $this->render('update', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Deletes an existing Account model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     */
    public function actionDelete($id)
    {
        $this->findModel($id)->delete();

        return $this->redirect(['index']);
    }

    /**
     * Lists all Account models.
     * @return mixed
     */
    public function actionList()
    {
        $searchModel = new AccountSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        return $this->render('list', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }

    /**
     * Finds the Account model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return Account the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = Account::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
<definitions
  xmlns="http://www.omg.org/spec/BPMN/20100524/MODEL"
  xmlns:camunda="http://camunda.org/schema/1.0/bpmn"
  targetNamespace="Examples">

  <process id="executionListenersProcess">
    <extensionElements>
      <camunda:executionListener class="org.camunda.bpm.engine.test.examples.bpmn.executionlistener.ExampleFieldInjectedExecutionListener" event="start">
        <camunda:field name="fixedValue" stringValue="Yes, I am " />
        <camunda:field name="dynamicValue" expression="${myVar}" />
      </camunda:executionListener>
    </extensionElements>

    <startEvent id="theStart" />
    <sequenceFlow sourceRef="theStart" targetRef="firstTask" />

    <userTask id="firstTask" />
    <sequenceFlow sourceRef="firstTask" targetRef="theEnd" />

    <endEvent id="theEnd" />
  </process>
</definitions>


text:
package org.robolectric.shadows;

import android.app.LoadedApk;
import org.robolectric.annotation.Implementation;
import org.robolectric.annotation.Implements;

@Implements(value = LoadedApk.class, isInAndroidSdk = false)
public class ShadowLoadedApk {

  @Implementation
  public ClassLoader getClassLoader() {
    return this.getClass().getClassLoader();
  }
}


text:
import '../styles.css';
import '../scssStyles.scss';

// Core
import {NgModule} from '@angular/core';

// Modules
import {DashboardModule} from "./dashboard/dashboard.module";
import {EnterpriseLibraryModule} from "./enterpriseLibrary/library.module";
import {UtilitiesModule} from "./utilities/utilities.module";
import {CodeSetModule} from "./codeSet/codeSet.module";
import {QueryModule} from "./query/query.module";

// State components
import {DashboardComponent} from "./dashboard/dashboard.component";
import {LibraryComponent} from "./enterpriseLibrary/library.component";
import {UtilitiesComponent} from "./utilities/utilities.component";
import {CodeSetEditComponent} from "./codeSet/codeSetEditor.component";
import {QueryEditComponent} from "./query/queryEditor.component";
import {Application} from "eds-common-js";
import {FlowchartModule} from "./flowchart/flowchart.module";
import {EnterpriseMenuService} from "./enterprise.menu";
import {ReportEditComponent} from "./report/reportEditor.component";
import {ReportModule} from "./report/report.module";
import {ChartModule} from "./charting/chart.module";

@NgModule(
	Application.Define({
		modules: [
			FlowchartModule,
			ChartModule,
			DashboardModule,
			UtilitiesModule,
			EnterpriseLibraryModule,
			CodeSetModule,
			QueryModule,
			ReportModule,
		],
		states: [
			{ name: 'app.dashboard', url: '/dashboard', component: DashboardComponent },
			{ name : 'app.library', url: '/library', component : LibraryComponent },
			{ name : 'app.utilityId', url: '/utilities/:utilId', component : UtilitiesComponent },
			{ name : 'app.utilities', url: '/utilities', component : UtilitiesComponent },
			{ name : 'app.codeSetEdit', url : '/codeSetEdit/:itemAction/:itemUuid', component : CodeSetEditComponent },
			{ name: 'app.queryEdit', url: '/queryEdit/:itemAction/:itemUuid', component: QueryEditComponent },
			{ name : 'app.reportEdit', url: '/reportEdit/:itemAction/:itemUuid', component: ReportEditComponent }
		],
		defaultState : { state: 'app.library', params: {} },
		menuManager : EnterpriseMenuService
	})
)
export class AppModule {}

Application.Run(AppModule);


text:
package org.apache.commons.configuration2;

import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
import java.io.Writer;
import java.util.Map;

import org.apache.commons.configuration2.ex.ConfigurationException;
import org.apache.commons.configuration2.io.InputStreamSupport;
import org.apache.commons.configuration2.tree.ImmutableNode;
import org.yaml.snakeyaml.DumperOptions;
import org.yaml.snakeyaml.LoaderOptions;
import org.yaml.snakeyaml.Yaml;

/**
 * <p>
 * A specialized hierarchical configuration class that is able to parse YAML
 * documents.
 * </p>
 *
 * @since 2.2
 */
public class FixedYAMLConfiguration extends FixedAbstractYAMLBasedConfiguration
        implements FileBasedConfiguration, InputStreamSupport
{
    /**
     * Creates a new instance of {@code FixedYAMLConfiguration}.
     */
    public FixedYAMLConfiguration()
    {
        super();
    }

    /**
     * Creates a new instance of {@code FixedYAMLConfiguration} as a copy of the
     * specified configuration.
     *
     * @param c the configuration to be copied
     */
    public FixedYAMLConfiguration(HierarchicalConfiguration<ImmutableNode> c)
    {
        super(c);
    }

    @Override
    public void read(Reader in) throws ConfigurationException
    {
        try
        {
            Yaml yaml = new Yaml();
            Map<String, Object> map = (Map) yaml.load(in);
            load(map);
        }
        catch (Exception e)
        {
            rethrowException(e);
        }
    }

    public void read(Reader in, LoaderOptions options)
            throws ConfigurationException
    {
        try
        {
            Yaml yaml = new Yaml(options);
            Map<String, Object> map = (Map) yaml.load(in);
            load(map);
        }
        catch (Exception e)
        {
            rethrowException(e);
        }
    }

    @Override
    public void write(Writer out) throws ConfigurationException, IOException
    {
        DumperOptions options = new DumperOptions();
        options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
        dump(out, options);
    }

    public void dump(Writer out, DumperOptions options)
            throws ConfigurationException, IOException
    {
        Yaml yaml = new Yaml(options);
        yaml.dump(constructMap(getNodeModel().getNodeHandler().getRootNode()),
                out);
    }

    /**
     * Loads the configuration from the given input stream.
     *
     * @param in the input stream
     * @throws ConfigurationException if an error occurs
     */
    @Override
    public void read(InputStream in) throws ConfigurationException
    {
        try
        {
            Yaml yaml = new Yaml();
            Map<String, Object> map = (Map) yaml.load(in);
            load(map);
        }
        catch (Exception e)
        {
            rethrowException(e);
        }
    }

    public void read(InputStream in, LoaderOptions options)
            throws ConfigurationException
    {
        try
        {
            Yaml yaml = new Yaml(options);
            Map<String, Object> map = (Map) yaml.load(in);
            load(map);
        }
        catch (Exception e)
        {
            rethrowException(e);
        }
    }

}


text:
<?xml version="1.0" encoding="UTF-8"?>
<beans>
	<bean id="admin" class="com.lwx.test.ioc.po.Admin">
		<property name="user" reference="user"/>
	</bean>
	<bean id="user" class="com.lwx.test.ioc.po.User">
		<property name="admin" reference="admin"/>
	</bean>
	<bean id="test" class="com.lwx.test.ioc.po.Test">
		<property name="admin" reference="admin"/>
		<property name="user" reference="user"/>
	</bean>
</beans>


text:
require 'timeout'

module Etcd
  module Mod
    # implement etcd lock module
    module Lock
      def mod_lock_endpoint
        '/mod/v2/lock'
      end

      def acquire_lock(key, ttl, opts = {})
        path = mod_lock_endpoint + key + "?ttl=#{ttl}"
        timeout = opts[:timeout] || 60
        Timeout.timeout(timeout) do
          return api_execute(path, :post, params: opts).body
        end
      end

      def renew_lock(key, ttl, opts = {})
        unless opts.key?(:index) || opts.key?(:value)
          fail ArgumentError, 'You mast pass index or value'
        end
        path = mod_lock_endpoint + key + "?ttl=#{ttl}"
        timeout = opts[:timeout] || 60
        Timeout.timeout(timeout) do
          api_execute(path, :put, params: opts).body
        end
      end

      def get_lock(key, opts = {})
        api_execute(mod_lock_endpoint + key, :get, params: opts).body
      end

      def delete_lock(key, opts = {})
        unless opts.key?(:index) || opts.key?(:value)
          fail ArgumentError, 'You must pass index or value'
        end
        api_execute(mod_lock_endpoint + key, :delete, params: opts)
      end

      # rubocop:disable RescueException
      def lock(key, ttl, opts = {})
        key = "/" + key unless key.start_with? '/'
        lock_index = acquire_lock(key, ttl, opts)
        begin
          yield key
        rescue Exception => e
          raise e
        ensure
          delete_lock(key, index: lock_index)
        end
      end
      # rubocop:enable RescueException

      alias_method :retrive_lock, :get_lock
      alias_method :release_lock, :delete_lock
    end
  end
end


text:
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace Svetsoft.Nmea.Tests
{
    [TestClass]
    public class DbtSentenceTests
    {
        /// <summary>
        ///     Checks whether a parsed DBT sentence from the NMEA specification equals the string it was built from.
        /// </summary>
        [TestMethod]
        public void ParseDbtSentence()
        {
            var sentence = new DbtSentence("$GPDBT,20.0,f,20.0,M,20.0,F*34");

            // NmeaSentence (Inherited)
            Assert.AreEqual("$GPDBT,20.0,f,20.0,M,20.0,F*34", sentence.Sentence);
            Assert.AreEqual("GPDBT", sentence.MessageType);
            Assert.AreEqual("34", sentence.Checksum);
            CollectionAssert.AreEqual(new[]
            {
                "20.0",
                "f",
                "20.0",
                "M",
                "20.0",
                "F"
            }, sentence.Fields);

            // DBT-specific
            Assert.AreEqual(20.0, sentence.FeetDepth.Value);
            Assert.AreEqual(DistanceUnit.Feet, sentence.FeetDepth.Unit);
            Assert.AreEqual(20.0, sentence.MetersDepth.Value);
            Assert.AreEqual(DistanceUnit.Meters, sentence.MetersDepth.Unit);
            Assert.AreEqual(20.0, sentence.FathomsDepth.Value);
            Assert.AreEqual(DistanceUnit.Fathoms, sentence.FathomsDepth.Unit);
        }
    }
}


text:
<?php
class Kwf_Model_Mongo_ChildRowsWithParentExpr_BothProxy_MongoModel extends Kwf_Model_Proxy
{
    protected function _init()
    {
        $this->_proxyModel = new Kwf_Model_Mongo_TestModel();
        $this->_dependentModels['Foo'] = new Kwf_Model_Mongo_RowsSubModel(array(
            'parentModel' => $this,
            'fieldName' => 'foo',
            'referenceMap' => array(
                'Parent' => array(
                    'refModelClass' => 'Kwf_Model_Mongo_ChildRowsWithParentExpr_BothProxy_ParentModel',
                    'column' => 'parent_id'
                ),
                'Mongo' => Kwf_Model_RowsSubModel_Interface::SUBMODEL_PARENT,
            ),
            'exprs' => array(
                'parent_name' => new Kwf_Model_Select_Expr_Parent('Parent', 'name'),
                'mongo_name' => new Kwf_Model_Select_Expr_Parent('Mongo', 'name'),
            )
        ));
        parent::_init();
    }
}


text:
/* */
"format cjs";
  /** Used to determine if values are of the language type Object */
  var dontEnums = ['toString',
    'toLocaleString',
    'valueOf',
    'hasOwnProperty',
    'isPrototypeOf',
    'propertyIsEnumerable',
    'constructor'],
  dontEnumsLength = dontEnums.length;


text:
package net.mnementh64.neural;

import net.mnementh64.neural.model.layer.Layer;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public class NetworkGeneticEvolution {

    private Random random = new Random(System.currentTimeMillis());

    public void checkSimilarity(Network network, Network other) {
        // both networks must be similar - same type, same number of layers and all layers with the same size / same activation function
        if ((other.layers.size() != network.layers.size())
        ) {
            throw new IllegalArgumentException("Can't crosssover 2 networks not similar");
        }

        // skip INPUT layer - genetic evolution only affect HIDDEN layers, so also rely on OUTPUT layer (for weights of the last layer)
        for (int i = 1; i < network.layers.size(); i++) {
            if (!network.layers.get(i).type.equals(other.layers.get(i).type) ||
                    network.layers.get(i).getNbNodes() != other.layers.get(i).getNbNodes() ||
                    !network.layers.get(i).activationFunction.equals(other.layers.get(i).activationFunction)) {
                throw new IllegalArgumentException("Can't crosssover 2 networks not similar");
            }
        }
    }

    /**
     * Single point binary crossover.
     * <p>
     * Create a new network with the same input / output and
     * 1) Random choice of a hidden layer.
     * 2) get network2's layers until this layer
     * 3) get network1's layers after this layer
     */
    public Network SPBX(Network network1, Network network2) {
        Network nextGenerationNetwork = new Network();
        List<Layer> newLayers = new ArrayList<>();

        // random selection of hidden layer to split
        int whichLayer = getRandomLayerForCrossover(network1.layers.size()); // can't be the input / output layers

        // copy all layers before the split one (including it) from the network 2
        for (int i = 0; i <= whichLayer; i++) {
            newLayers.add(network2.layers.get(i).clone());
        }

        // copy all layers after the split one from network 1
        for (int i = whichLayer + 1; i < network1.layers.size(); i++) {
            newLayers.add(network1.layers.get(i).clone());
        }

        nextGenerationNetwork.layers = newLayers;
        return nextGenerationNetwork;
    }

    public void mutate(Network network, double mutationRate, boolean applyExtremValue, double minValue, double maxValue) {
        if (mutationRate >= 1.0) {
            throw new IllegalArgumentException("Mutation rate should be strictly less than 1");
        }
        for (int layerIndex = 0; layerIndex < network.layers.size() - 1; layerIndex++) {
            Layer layer = network.layers.get(layerIndex);
            for (int i = 0; i < layer.getNbNodes(); i++) {
                for (int j = 0; j < network.layers.get(layerIndex + 1).getNbNodes(); j++) {
                    if (random.nextDouble() < mutationRate) {
                        layer.weightsToNext[i][j] += random.nextGaussian() / 5;

                        if (applyExtremValue) {
                            if (layer.weightsToNext[i][j] > maxValue) {
                                layer.weightsToNext[i][j] = maxValue;
                            }
                            if (layer.weightsToNext[i][j] < minValue) {
                                layer.weightsToNext[i][j] = minValue;
                            }
                        }
                    }
                }
            }
        }
    }

    int getRandomLayerForCrossover(int nbLayers) {
        // random selection of hidden layer to split
        return random.nextInt(nbLayers - 2) + 1;
    }
}


text:
import React from 'react';
import Listing from 'views/Listing';

export default class CourseList extends Listing {
  constructor(props) {
    super(props);
    this.itemType = 'course';
    this.title = 'What course?';
    this.back = <a className="goback btn block" href="#" onClick={() => ::this.resetChoice('club')}>← CHANGE CLUB </a>;
  }
}


text:
/* global describe, inject, it, beforeEach, expect*/

import angular from 'angular';
import Tester from 'tester';

import '..';

describe('avTemplateCache', () => {

  let $httpBackend;
  let avTemplateCache;
  const tester = new Tester();

  beforeEach(() => {
    angular.mock.module('availity');
    angular.mock.module('availity.ui');
  });

  beforeEach(inject((_$httpBackend_, _avTemplateCache_) => {
    $httpBackend = _$httpBackend_;
    avTemplateCache = _avTemplateCache_;
  }));

  tester.service();

  const html = '
hi
';

  it('should respond with markup with option `template`', () => {

    const options = {template: html};

    avTemplateCache.get(options).then(template => {
      expect(template).toBe(html);
    });

    tester.$scope.$apply();

  });

  it('should respond with markup with option `tempalteUrl`', () => {

    $httpBackend.expectGET('demo/tpl.html').respond(html);

    const options = {templateUrl: 'demo/tpl.html'};

    avTemplateCache.get(options).then(template => {
      expect(template).toBe(html);
    });

    $httpBackend.flush();
    tester.$scope.$apply();

  });

});


text:
"use strict";
let jefferson = require("express-jefferson");
let manufacturers = require("../../../middleware/manufacturers");
let cache = require("../../../middleware/cache");

module.exports = jefferson.router({
    proxies: [require("express-jefferson/proxies/promise-handler")],
    pre: {
        all: [cache({maxAge: 3600})]
    },
    routes: {
        "/": {
            get: [manufacturers.getManufacturerByName]
        }
    }
});


text:
<?php

    abstract class LocalizableExceptionDefinition {
        static public $FETCH_IN_PROGRESS_ERROR = "FETCH_IN_PROGRESS_ERROR";
        static public $FETCH_FAILED_ERROR = "FETCH_FAILED_ERROR";
        static public $PRIVATE_KEY_LOAD_ERROR = "PRIVATE_KEY_LOAD_ERROR";
        static public $PUBLIC_KEY_LOAD_ERROR = "PUBLIC_KEY_LOAD_ERROR";
        static public $DECRYPT_ERROR = "DECRYPT_ERROR";
        static public $CONNECTION_FAILURE_ERROR = "CONNECTION_FAILURE_ERROR";
        static public $UNCONNECTED_DISCONNECT_ERROR = "UNCONNECTED_DISCONNECT_ERROR";
        static public $FILE_DOES_NOT_EXIST_ERROR = "FILE_DOES_NOT_EXIST_ERROR";
        static public $FILE_EXISTS_ERROR = "FILE_EXISTS_ERROR";
        static public $FILE_PERMISSION_ERROR = "FILE_PERMISSION_ERROR";
        static public $GENERAL_FILE_SOURCE_ERROR = "GENERAL_FILE_SOURCE_ERROR";
        static public $OPERATION_BEFORE_CONNECTION_ERROR = "OPERATION_BEFORE_CONNECTION_ERROR";
        static public $OPERATION_BEFORE_AUTHENTICATION_ERROR = "OPERATION_BEFORE_CONNECTION_ERROR";
        static public $AUTHENTICATION_BEFORE_CONNECTION_ERROR = "AUTHENTICATION_BEFORE_CONNECTION_ERROR";
        static public $PASSIVE_MODE_BEFORE_AUTHENTICATION_ERROR = "PASSIVE_MODE_BEFORE_AUTHENTICATION_ERROR";
        static public $FAILED_TO_SET_PASSIVE_MODE_ERROR = "FAILED_TO_SET_PASSIVE_MODE_ERROR";
        static public $AUTHENTICATION_FAILED_ERROR = "AUTHENTICATION_FAILED_ERROR";
        static public $LICENSE_READ_FAILED_ERROR = "LICENSE_READ_FAILED_ERROR";
        static public $LIST_DIRECTORY_FAILED_ERROR = "LIST_DIRECTORY_FAILED_ERROR";
        static public $GET_SYSTEM_TYPE_BEFORE_CONNECTION_ERROR = "GET_SYSTEM_TYPE_FAILED_ERROR";
        static public $GET_SYSTEM_TYPE_FAILED_ERROR = "GET_SYSTEM_TYPE_FAILED_ERROR";
        static public $FAILED_TO_CLOSE_CONNECTION_ERROR = "FAILED_TO_CLOSE_CONNECTION_ERROR";
        static public $GET_WORKING_DIRECTORY_BEFORE_CONNECTION_ERROR = "GET_WORKING_DIRECTORY_BEFORE_CONNECTION_ERROR";
        static public $DEBIAN_PRIVATE_KEY_BUG_ERROR = "DEBIAN_PRIVATE_KEY_BUG_ERROR";
        static public $COULD_NOT_LOAD_PROFILE_DATA_ERROR = "COULD_NOT_LOAD_PROFILE_DATA_ERROR";
        static public $PROFILE_NOT_READABLE_ERROR = "PROFILE_NOT_READABLE_ERROR";
        static public $PROFILE_SIZE_READ_ERROR = "PROFILE_SIZE_READ_ERROR";
        static public $UNSUPPORTED_CIPHER_ERROR = "UNSUPPORTED_CIPHER_ERROR";
        static public $PROBABLE_INCORRECT_PASSWORD_ERROR = "PROBABLE_INCORRECT_PASSWORD_ERROR";
        static public $IV_GENERATE_ERROR = "IV_GENERATE_ERROR";
        static public $SETTINGS_READ_ERROR = "SETTINGS_READ_ERROR";
        static public $SETTINGS_WRITE_ERROR = "SETTINGS_WRITE_ERROR";
        static public $ARCHIVE_READ_ERROR = "ARCHIVE_READ_ERROR";
        static public $LICENSE_WRITE_ERROR = "LICENSE_WRITE_ERROR";
        static public $PRO_CONFIG_WRITE_ERROR = "PRO_CONFIG_WRITE_ERROR";
        static public $REPLACEMENT_LICENSE_OLDER_ERROR = "REPLACEMENT_LICENSE_OLDER_ERROR";
        static public $INVALID_POSTED_LICENSE_ERROR = "INVALID_POSTED_LICENSE_ERROR";
        static public $SFTP_AUTHENTICATION_NOT_ENABLED = "SFTP_AUTHENTICATION_NOT_ENABLED";
    }

    // i wanted this to be a static member on LocalizableExceptionCodeLookup but then i would have to instantiate it
    // every time due to PHP not allowing expressions in class definitions. this global is the lesser of two evils
    // or make it a singleton soon
    // todo make LocalizableExceptionCodeLookup a singleton
    $EXCEPTION_CODE_MAP = array(
        LocalizableExceptionDefinition::$FETCH_IN_PROGRESS_ERROR,
        LocalizableExceptionDefinition::$FETCH_FAILED_ERROR,
        LocalizableExceptionDefinition::$PRIVATE_KEY_LOAD_ERROR,
        LocalizableExceptionDefinition::$PUBLIC_KEY_LOAD_ERROR,
        LocalizableExceptionDefinition::$DECRYPT_ERROR,
        LocalizableExceptionDefinition::$CONNECTION_FAILURE_ERROR,
        LocalizableExceptionDefinition::$UNCONNECTED_DISCONNECT_ERROR,
        LocalizableExceptionDefinition::$FILE_DOES_NOT_EXIST_ERROR,
        LocalizableExceptionDefinition::$FILE_EXISTS_ERROR,
        LocalizableExceptionDefinition::$FILE_PERMISSION_ERROR,
        LocalizableExceptionDefinition::$GENERAL_FILE_SOURCE_ERROR,
        LocalizableExceptionDefinition::$OPERATION_BEFORE_CONNECTION_ERROR,
        LocalizableExceptionDefinition::$OPERATION_BEFORE_AUTHENTICATION_ERROR,
        LocalizableExceptionDefinition::$AUTHENTICATION_BEFORE_CONNECTION_ERROR,
        LocalizableExceptionDefinition::$PASSIVE_MODE_BEFORE_AUTHENTICATION_ERROR,
        LocalizableExceptionDefinition::$FAILED_TO_SET_PASSIVE_MODE_ERROR,
        LocalizableExceptionDefinition::$AUTHENTICATION_FAILED_ERROR,
        LocalizableExceptionDefinition::$LICENSE_READ_FAILED_ERROR,
        LocalizableExceptionDefinition::$LIST_DIRECTORY_FAILED_ERROR,
        LocalizableExceptionDefinition::$GET_SYSTEM_TYPE_BEFORE_CONNECTION_ERROR,
        LocalizableExceptionDefinition::$GET_SYSTEM_TYPE_FAILED_ERROR,
        LocalizableExceptionDefinition::$FAILED_TO_CLOSE_CONNECTION_ERROR,
        LocalizableExceptionDefinition::$GET_WORKING_DIRECTORY_BEFORE_CONNECTION_ERROR,
        LocalizableExceptionDefinition::$DEBIAN_PRIVATE_KEY_BUG_ERROR,
        LocalizableExceptionDefinition::$COULD_NOT_LOAD_PROFILE_DATA_ERROR,
        LocalizableExceptionDefinition::$PROFILE_NOT_READABLE_ERROR,
        LocalizableExceptionDefinition::$PROFILE_SIZE_READ_ERROR,
        LocalizableExceptionDefinition::$UNSUPPORTED_CIPHER_ERROR,
        LocalizableExceptionDefinition::$PROBABLE_INCORRECT_PASSWORD_ERROR,
        LocalizableExceptionDefinition::$IV_GENERATE_ERROR,
        LocalizableExceptionDefinition::$SETTINGS_READ_ERROR,
        LocalizableExceptionDefinition::$SETTINGS_WRITE_ERROR,
        LocalizableExceptionDefinition::$ARCHIVE_READ_ERROR,
        LocalizableExceptionDefinition::$LICENSE_WRITE_ERROR,
        LocalizableExceptionDefinition::$PRO_CONFIG_WRITE_ERROR,
        LocalizableExceptionDefinition::$REPLACEMENT_LICENSE_OLDER_ERROR,
        LocalizableExceptionDefinition::$INVALID_POSTED_LICENSE_ERROR,
        LocalizableExceptionDefinition::$SFTP_AUTHENTICATION_NOT_ENABLED
    );

    abstract class LocalizableExceptionCodeLookup {
        static function codeToName($errorCode) {
            global $EXCEPTION_CODE_MAP;
            return $EXCEPTION_CODE_MAP[$errorCode];
        }

        static function nameToCode($errorName) {
            global $EXCEPTION_CODE_MAP;
            return array_search($errorName, $EXCEPTION_CODE_MAP);
        }
    }

    class LocalizableException extends Exception {
        /**
         * @var array
         */
        private $context;

        public function __construct($message, $errorName, $context = null, $previous = null) {
            $code = LocalizableExceptionCodeLookup::nameToCode($errorName);

            parent::__construct($message, $code, $previous);

            $this->context = $context;
        }

        /**
         * @return array
         */
        public function getContext() {
            return $this->context;
        }
    }


text:
from distutils.core import setup
from commands import getoutput

version = getoutput('git describe --always') or '1.0'

setup(name='unifi',
      version=version,
      description='API towards Ubiquity Networks UniFi controller',
      author='Jakob Borg',
      author_email='jakob@nym.se',
      url='https://github.com/calmh/unifi-api',
      packages=['unifi'],
      scripts=['unifi-low-snr-reconnect', 'unifi-ls-clients', 'unifi-save-statistics'],
      classifiers=['Development Status :: 4 - Beta',
          'Intended Audience :: Developers',
          'License :: OSI Approved :: MIT License',
          'Topic :: Software Development :: Libraries',
          'Topic :: System :: Networking']
     )


text:
package jTuples.homogeneous;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import jtuples.Tuple2;

public class HTuple<T> implements HTupleInterface<T> {

    private final ArrayList<T> items;

    @SafeVarargs
    public HTuple(T... ts) {
        this.items = (ArrayList<T>) Arrays.asList(ts);
    }

    @Override
    public List<T> take(int n) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public HTupleInterface<T> takeT(int n) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public HTupleInterface<T> remove(T t) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public HTupleInterface<T> remove(int i) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public HTupleInterface<T> append(String s) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public HTupleInterface<T> drop(T t) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public HTuple<Tuple2<Integer, T>> enumerate() {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public HTuple<Tuple2<Integer, T>> enumerate(int begin) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public HTuple<Tuple2<Integer, T>> enumerate(int begin, int step) {
        // TODO Auto-generated method stub
        return null;
    }

}


text:
layout: post
title: "Collaborative development with Git"
date: 2016-12-12 21:31:05
description: "consider the way that you contribute with teams, how important it is for large projects which requires organization and maintenance."
main-class: 'dev'
color: '#637a91'
tags:
- "git"
- "workflow"
- "productivity"
image: "/assets/img/icons/git.svg"
twitter_text: "A thought on the effective contribution using git..."
introduction: "A thought about practices in the contribution of projects within teams."
---

Is remarkable the growing demand of using version control systems, allowing and encouraging us to have multiple branches that can be entirely independent of each other. In this article will be discussed about the basics of common Git workflows used by enterprise teams.

To follow this article make sure to be comfortable with basic knowledge of git, so if you are not so familiar with version control systems I encourage you to follow this great [guide](http://rogerdudler.github.io/git-guide/index.html) for beginners.

## Git Workflows

There are several workflows for git and it's use case vary of a set of circumstances that you and your team should reflect over very carefully. For this reason, in this article I'll be showing more carefully the available workflows and give you a better understanding of how they work.

Well then, to get us started I'd like to show you the most popular workflows that will be discussed in this article, these are:

1. [Centralized Workflow](#centralized-workflow)
2. [Feature Branch Workflow](#feature-branch-workflow)
3. [Gitflow Workflow](#gitflow-workflow)
4. [Forking Workflow](#forking-workflow)

### Centralized Workflow
When you finish a feature, you may want to share your local working copy to a `remote repository`. In order to achieve this goal we could use a Centralized Workflow to provide a single point-of-entry for all changes to the project, allowing collaboration and streamline communication between developers.

Basically developers work on a feature in a `private local` one and sync with a `remote repository`, providing two main **branchs**.

![Git Repositories]({{site.baseurl}}/assets/img/method-draw-image.svg)

So when your current work is finished and you want to synchronize with a remote repository you would follow this flow below:

{% highlight css %}
(master *)$ git commit -am "my changes"
(master *)$ git pull origin master
(master *)$ git push origin master
{% endhighlight %}

However are certain drawbacks that you should be aware, as `recursive merges` that may happen when you synchronize with a repository and that ends up by affecting the `commit history`, as seen below:

![asdas]({{site.baseurl}}/assets/img/logs.png)

To prevent this from happening and staying with a clear and linear commit history there are bunch of approaches and one of them  that I'll be showing here is called `rebase`, as you can see in the code snipped below:

{% highlight css %}
(master *)$ git pull --rebase origin master
{% endhighlight %}

To wind up this topic, you may be wondering in which cases a centralized workflow can be useful. Well, in my option it may be convenient mostly for very basic projects by the simplicity  and learning curve provided by this workflow.

### Feature Branch Workflow
Imagine that you have to implement a `shopping cart` feature and while you are developing that you don't want to affect the production environment, to archive this goal you could use a **feature branch**:

{% highlight css %}
(master *)$ git checkout -b shopping_cart
  Switched to a new branch 'shopping_cart'

(shopping_cart *)$ git push origin shopping_cart
  * [new branch] shopping_cart -> shopping_cart
{% endhighlight %}

Once this new branch has been created, you will have a separated branch tracked with the remote repository and you can comfortably implement your features in a dedicated branch without affect the production environment of the application.

When the implementation of this feature is completed you now will need to share the code you have made simply by merging to (master) production:

{% highlight css %}
(shopping_cart *)$ git rebase master
(shopping_cart *)$ git checkout master
  * Switched to branch 'master'

(master *)$ git merge shopping_cart
(master *)$ git push origin master
{% endhighlight %}

After the merge, at this point the `shopping_cart` branch may not be as useful anymore and you may want to remove it from the branchs:

{% highlight css %}
(master *)$ git push origin :shopping_cart
  - [deleted] shopping_cart

(master *)$ git branch -D shopping_cart
  Deleted branch shopping_cart
{% endhighlight %}

So we can  bring to a conclusion that this workflow is commonly useful for adding new features and a special attention should be paid. From there, you encapsulate a particular feature without disturbing the main codebase into `master` branch, avoiding failures such as in a production environment.

### Gitflow Workflow
The ideia behind **Gitflow** is very similar to the [Feature Branch](#feature-branch-workflow) that in fact both can work together. However, there are certain concepts  which should be taken into account, such as `branches`, `releases` and `tags`.

Before anything else we should not use the `master` as the parent of our branches. Instead, we usually create other branches to put our commits, like hotfixes, acceptance tests or a good one example as a development branch created below:

{% highlight css %}
(master *)$ git checkout -b development
  Switched to a new branch 'development'

(development *)$ git push origin development
  * [new branch] development -> development
{% endhighlight %}

From now on, when new features come ready to production, we create a `release branch` as a delivery of what we done in the development branch:

{% highlight css %}
(development *)$ git checkout -b release-1.0 development
  Switched to a new branch 'release-1.0'

(release-1 *)$ git tag v1.1.1 -m "shopping cart feature"
{% endhighlight %}

Another idea that we must take in practice from the above code snippet is the use of `tags`, every time you push to production, use them to keep track of all production releases. Generally you only need tags for releases, but pay attention to them, tags are regarded as documentation! If you want more information on naming your tags, a great place to go is the [Semantic Version 2.0.0](http://semver.org/).

In order to put a new release to production, we can do as follows:

{% highlight css %}
(release-1 *)$ git checkout master
  Switched to branch 'master'

(master *)$ git merge release-1.0
(master *)$ git push origin master
(master *)$ git tag v1.0.0
(master *)$ git push origin --tags
{% endhighlight %}

To finish this section, **Gitflow** may be desirable for large project, bringing with it improvements such as a stable master branch, ease of code review and helps to avoid late integration of features. However, you should consider knowledge in Git amoung the members of your team, keep in mind that **Gitflow** is complex. Notice that are topics which should be further explored such as the *use cases* for release branches, *types of tags*, etc.

### Forking Workflow
All that has been said so far was thought from the point of view of private corporate environments. But most projects hosted on services such as *GitHub*  are certainly open source, whence provides push permissions flexibly to non-collaborators from a repository easily as shown below:

{% highlight css %}
# 1. You need fork and clone a repository
# 2. Create your feature branch:
  $ git checkout -b my-new-feature
# 3. Commit your changes:
  $ git commit -m 'Add some feature'
# 4. Push to the branch:
  $ git push origin my-new-feature
# 5. Submit a pull request
{% endhighlight %}

When you send a pull request, the owner of the original repository is then notified, check your pull request and decide to accept or not, accepting it is then created a *merge commit*. Other users can also review your branch, commit and add their changes to your pull request, besides that anyone can comment on PR.

Thinking on huge projects such as Linux kernel, having thousands of collaborators there also **Dictator and Lieutenants** workflow, where various integration managers are in charge of certain parts of the repository.

## Conclusion
I hope I have made clear the ideia to follow a workflow for a better experience along with teams, make sure to pick a good one which fits in your project and use it always in favor of the collaborators, also putting into practice the basic knowledge on good practices as small and expressive commits among individual developers.

Just to finish, do not stop your knowledge here, you can start reading the excellent [Git Pro](https://git-scm.com/book/en/v2) book and learn more about git basics, tools, environments, servers and more through a complete content for free.


text:
import { module, test } from 'qunit';
import { setupIntegrationTest } from 'open-event-frontend/tests/helpers/setup-integration-test';
import hbs from 'htmlbars-inline-precompile';
import { render } from '@ember/test-helpers';

module('Integration | Component | ui table/header rows grouped', function(hooks) {
  setupIntegrationTest(hooks);

  const groupedHeaders = [[{ title: 'Cat1' }], [{ title: 'Cat2' }]];
  test('it renders', async function(assert) {
    this.set('groupedHeaders', groupedHeaders);
    await render(hbs `{{ui-table/header-rows-grouped groupedHeaders=groupedHeaders}}`);
    assert.ok(this.element.innerHTML.trim().includes('Cat1'));
  });
});


text:
-- --------------------------------------------------------
-- Host:                         127.0.0.1
-- Server version:               5.5.44-MariaDB-log - FreeBSD Ports
-- Server OS:                    FreeBSD10.1
-- HeidiSQL Version:             9.3.0.4984
-- --------------------------------------------------------

/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET NAMES utf8mb4 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;

-- Dumping structure for table mlanglois_SEG2105_Final.Goals
CREATE TABLE IF NOT EXISTS `Goals` (
  `Goal_ID` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `Player_ID` int(10) unsigned NOT NULL,
  `Assist_ID` int(10) unsigned DEFAULT NULL,
  `Match_ID` int(10) unsigned NOT NULL,
  `Team_ID` int(10) unsigned NOT NULL,
  `Last_Update_Datetime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`Goal_ID`),
  KEY `Player_ID` (`Player_ID`),
  KEY `Assist_ID` (`Assist_ID`),
  KEY `Match_ID` (`Match_ID`),
  KEY `Team_ID` (`Team_ID`),
  CONSTRAINT `Goals_ibfk_4` FOREIGN KEY (`Team_ID`) REFERENCES `Teams` (`Team_ID`),
  CONSTRAINT `Goals_ibfk_1` FOREIGN KEY (`Player_ID`) REFERENCES `Persons` (`Person_ID`),
  CONSTRAINT `Goals_ibfk_2` FOREIGN KEY (`Assist_ID`) REFERENCES `Persons` (`Person_ID`),
  CONSTRAINT `Goals_ibfk_3` FOREIGN KEY (`Match_ID`) REFERENCES `Matches` (`Match_ID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

-- Dumping data for table mlanglois_SEG2105_Final.Goals: ~0 rows (approximately)
/*!40000 ALTER TABLE `Goals` DISABLE KEYS */;
/*!40000 ALTER TABLE `Goals` ENABLE KEYS */;
/*!40101 SET SQL_MODE=IFNULL(@OLD_SQL_MODE, '') */;
/*!40014 SET FOREIGN_KEY_CHECKS=IF(@OLD_FOREIGN_KEY_CHECKS IS NULL, 1, @OLD_FOREIGN_KEY_CHECKS) */;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;


text:
var fse = require("fs-extra");
var path = require("path");
var local = path.join.bind(path, __dirname);
var exec = require('../utils/execPromise');

var NodeGit = require('..');

var workdirPath = local("repos/workdir");
var constWorkdirPath = local("repos/constworkdir");

before(function() {
  this.timeout(350000);

  var url = "https://github.com/nodegit/test";
  return fse.remove(local("repos"))
    .then(function() {
      fse.remove(local("home"))
    })
    .then(function() {
      fse.mkdir(local("repos"));
    })
    .then(function() {
      return exec("git init " + local("repos", "empty"));
    })
    .then(function() {
      return exec("git clone " + url + " " + constWorkdirPath);
    })
    .then(function() {
      return exec("git clone " + url + " " + workdirPath);
    })
    .then(function() {
      return exec("git checkout rev-walk", {cwd: workdirPath});
    })
    .then(function() {
      return exec("git checkout checkout-test", {cwd: workdirPath});
    })
    .then(function() {
      return exec("git checkout master", {cwd: workdirPath});
    })
    .then(function() {
      return fse.mkdir(local("repos", "nonrepo"));
    })
    .then(function() {
      return fse.writeFile(local("repos", "nonrepo", "file.txt"),
        "This is a bogus file");
    })
    .then(function() {
      return fse.mkdir(local("home"));
    })
    .then(function() {
      return fse.writeFile(local("home", ".gitconfig"),
        "[user]\n  name = John Doe\n  email = johndoe@example.com");
    });
});

beforeEach(function() {
  this.timeout(4000);
  return exec("git clean -xdf", {cwd: workdirPath})
  .then(function() {
    return exec("git checkout master", {cwd: workdirPath});
  })
  .then(function() {
    return exec("git reset --hard", {cwd: workdirPath});
  });
});

afterEach(function(done) {
  process.nextTick(function() {
    if (global.gc) {
      global.gc();
    }
    done();
  });
});


text:
/*
 * A wrapper around printf. Not thread-safe due to the global variable
 * DEBUG.
 */

#include <stdio.h>
#include <stdarg.h>
#include <stdbool.h>

bool DEBUG = false;

void debug_enable(bool enable)
{
    DEBUG = enable;
}

int debug_printf(char *format, ...)
{
    if (!DEBUG)
    {
        return 0;
    }

    va_list args;
    va_start(args, format);
    return printf(format, args);
}


text:
<Type Name="AVPlayerItemOutput" FullName="MonoMac.AVFoundation.AVPlayerItemOutput">
  <TypeSignature Language="C#" Value="public class AVPlayerItemOutput : MonoMac.Foundation.NSObject" />
  <TypeSignature Language="ILAsm" Value=".class public auto ansi beforefieldinit AVPlayerItemOutput extends MonoMac.Foundation.NSObject" />
  <AssemblyInfo>
    <AssemblyName>MonoMac</AssemblyName>
    <AssemblyVersion>0.0.0.0</AssemblyVersion>
  </AssemblyInfo>
  <Base>
    <BaseTypeName>MonoMac.Foundation.NSObject</BaseTypeName>
  </Base>
  <Interfaces />
  <Attributes>
    <Attribute>
      <AttributeName>MonoMac.Foundation.Register("AVPlayerItemOutput", true)</AttributeName>
    </Attribute>
  </Attributes>
  <Docs>
    To be added.
    <remarks>To be added.</remarks>
  </Docs>
  <Members>
    <Member MemberName=".ctor">
      <MemberSignature Language="C#" Value="public AVPlayerItemOutput (MonoMac.Foundation.NSCoder coder);" />
      <MemberSignature Language="ILAsm" Value=".method public hidebysig specialname rtspecialname instance void .ctor(class MonoMac.Foundation.NSCoder coder) cil managed" />
      <MemberType>Constructor</MemberType>
      <AssemblyInfo>
        <AssemblyVersion>0.0.0.0</AssemblyVersion>
      </AssemblyInfo>
      <Attributes>
        <Attribute>
          <AttributeName>MonoMac.Foundation.Export("initWithCoder:")</AttributeName>
        </Attribute>
        <Attribute>
          <AttributeName>System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Advanced)</AttributeName>
        </Attribute>
      </Attributes>
      <Parameters>
        <Parameter Name="coder" Type="MonoMac.Foundation.NSCoder" />
      </Parameters>
      <Docs>
        <param name="coder">To be added.</param>
        To be added.
        <remarks>To be added.</remarks>
      </Docs>
    </Member>
    <Member MemberName=".ctor">
      <MemberSignature Language="C#" Value="public AVPlayerItemOutput (MonoMac.Foundation.NSObjectFlag t);" />
      <MemberSignature Language="ILAsm" Value=".method public hidebysig specialname rtspecialname instance void .ctor(class MonoMac.Foundation.NSObjectFlag t) cil managed" />
      <MemberType>Constructor</MemberType>
      <AssemblyInfo>
        <AssemblyVersion>0.0.0.0</AssemblyVersion>
      </AssemblyInfo>
      <Attributes>
        <Attribute>
          <AttributeName>System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Advanced)</AttributeName>
        </Attribute>
      </Attributes>
      <Parameters>
        <Parameter Name="t" Type="MonoMac.Foundation.NSObjectFlag" />
      </Parameters>
      <Docs>
        <param name="t">To be added.</param>
        To be added.
        <remarks>To be added.</remarks>
      </Docs>
    </Member>
    <Member MemberName=".ctor">
      <MemberSignature Language="C#" Value="public AVPlayerItemOutput (IntPtr handle);" />
      <MemberSignature Language="ILAsm" Value=".method public hidebysig specialname rtspecialname instance void .ctor(native int handle) cil managed" />
      <MemberType>Constructor</MemberType>
      <AssemblyInfo>
        <AssemblyVersion>0.0.0.0</AssemblyVersion>
      </AssemblyInfo>
      <Attributes>
        <Attribute>
          <AttributeName>System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Advanced)</AttributeName>
        </Attribute>
      </Attributes>
      <Parameters>
        <Parameter Name="handle" Type="System.IntPtr" />
      </Parameters>
      <Docs>
        <param name="handle">To be added.</param>
        To be added.
        <remarks>To be added.</remarks>
      </Docs>
    </Member>
    <Member MemberName="ClassHandle">
      <MemberSignature Language="C#" Value="public override IntPtr ClassHandle { get; }" />
      <MemberSignature Language="ILAsm" Value=".property instance native int ClassHandle" />
      <MemberType>Property</MemberType>
      <AssemblyInfo>
        <AssemblyVersion>0.0.0.0</AssemblyVersion>
      </AssemblyInfo>
      <ReturnValue>
        <ReturnType>System.IntPtr</ReturnType>
      </ReturnValue>
      <Docs>
        To be added.
        <value>To be added.</value>
        <remarks>To be added.</remarks>
      </Docs>
    </Member>
    <Member MemberName="GetItemTime">
      <MemberSignature Language="C#" Value="public virtual MonoMac.CoreMedia.CMTime GetItemTime (double hostTimeInSeconds);" />
      <MemberSignature Language="ILAsm" Value=".method public hidebysig newslot virtual instance valuetype MonoMac.CoreMedia.CMTime GetItemTime(float64 hostTimeInSeconds) cil managed" />
      <MemberType>Method</MemberType>
      <AssemblyInfo>
        <AssemblyVersion>0.0.0.0</AssemblyVersion>
      </AssemblyInfo>
      <Attributes>
        <Attribute>
          <AttributeName>MonoMac.Foundation.Export("itemTimeForHostTime:")</AttributeName>
        </Attribute>
      </Attributes>
      <ReturnValue>
        <ReturnType>MonoMac.CoreMedia.CMTime</ReturnType>
      </ReturnValue>
      <Parameters>
        <Parameter Name="hostTimeInSeconds" Type="System.Double" />
      </Parameters>
      <Docs>
        <param name="hostTimeInSeconds">To be added.</param>
        To be added.
        <returns>To be added.</returns>
        <remarks>To be added.</remarks>
      </Docs>
    </Member>
    <Member MemberName="GetItemTime">
      <MemberSignature Language="C#" Value="public virtual MonoMac.CoreMedia.CMTime GetItemTime (long machAbsoluteTime);" />
      <MemberSignature Language="ILAsm" Value=".method public hidebysig newslot virtual instance valuetype MonoMac.CoreMedia.CMTime GetItemTime(int64 machAbsoluteTime) cil managed" />
      <MemberType>Method</MemberType>
      <AssemblyInfo>
        <AssemblyVersion>0.0.0.0</AssemblyVersion>
      </AssemblyInfo>
      <Attributes>
        <Attribute>
          <AttributeName>MonoMac.Foundation.Export("itemTimeForMachAbsoluteTime:")</AttributeName>
        </Attribute>
      </Attributes>
      <ReturnValue>
        <ReturnType>MonoMac.CoreMedia.CMTime</ReturnType>
      </ReturnValue>
      <Parameters>
        <Parameter Name="machAbsoluteTime" Type="System.Int64" />
      </Parameters>
      <Docs>
        <param name="machAbsoluteTime">To be added.</param>
        To be added.
        <returns>To be added.</returns>
        <remarks>To be added.</remarks>
      </Docs>
    </Member>
    <Member MemberName="SuppressesPlayerRendering">
      <MemberSignature Language="C#" Value="public virtual bool SuppressesPlayerRendering { get; set; }" />
      <MemberSignature Language="ILAsm" Value=".property instance bool SuppressesPlayerRendering" />
      <MemberType>Property</MemberType>
      <AssemblyInfo>
        <AssemblyVersion>0.0.0.0</AssemblyVersion>
      </AssemblyInfo>
      <Attributes>
        <Attribute>
          <AttributeName>get: MonoMac.Foundation.Export("suppressesPlayerRendering")</AttributeName>
        </Attribute>
        <Attribute>
          <AttributeName>set: MonoMac.Foundation.Export("setSuppressesPlayerRendering:")</AttributeName>
        </Attribute>
      </Attributes>
      <ReturnValue>
        <ReturnType>System.Boolean</ReturnType>
      </ReturnValue>
      <Docs>
        To be added.
        <value>To be added.</value>
        <remarks>To be added.</remarks>
      </Docs>
    </Member>
  </Members>
</Type>


text:
(function () {
    'use strict';

    const factory = function () {

        class PromiseControl {

            /**
             * @param {Promise} promise
             */
            constructor(promise) {
                this.id = null;
                /**
                 * @type {Array}
                 * @private
                 */
                this._resolveCallbacks = [];
                /**
                 * @type {Array}
                 * @private
                 */
                this._rejectCallbacks = [];
                /**
                 * @type {*}
                 * @private
                 */
                this._data = null;
                /**
                 * @type {boolean|null}
                 * @private
                 */
                this._state = null;
                /**
                 * @type {boolean}
                 * @private
                 */
                this._dropped = false;
                /**
                 * @type {Promise}
                 * @private
                 */
                this._promise = promise;

                promise.then(this._getPromiseCallback(true), this._getPromiseCallback(false));
            }

            promise() {
                return this._promise;
            }

            abort(error) {
                this._getPromiseCallback(false)(error);
            }

            /**
             * @param {Function|null} resolve
             * @param {Function|null} [reject]
             * @return {PromiseControl}
             */
            then(resolve, reject) {
                return new PromiseControl(new Promise((res, rej) => {
                    this._resolveCallbacks.push((data) => {
                        const result = resolve ? resolve(data) : data;
                        if (PromiseControl.isPromise(result)) {
                            result.then(res, rej);
                        } else {
                            res(result);
                        }
                    });
                    this._rejectCallbacks.push((data) => {
                        const result = reject ? reject(data) : data;
                        if (PromiseControl.isPromise(result)) {
                            result.then(res, rej);
                        } else {
                            rej(result);
                        }
                    });
                }));
            }

            /**
             * @param cb
             * @return {PromiseControl}
             */
            always(cb) {
                this.then(cb, cb);
                return this;
            }

            /**
             * @param callback
             * @return {PromiseControl}
             */
            catch(callback) {
                return this.then(null, callback);
            }

            drop() {
                this._removeHandlers();
                this._dropped = true;
            }

            _getPromiseCallback(state) {
                return (data) => {
                    if (this._state === null) {
                        this._data = data;
                        this._state = state;
                        this._run();
                    }
                };
            }

            _run() {
                if (this._dropped || this._state === null) {
                    return null;
                }
                const list = (this._state ? this._resolveCallbacks : this._rejectCallbacks).slice();
                this._removeHandlers();
                list.forEach(cb => cb(this._data));
            }

            _removeHandlers() {
                this._rejectCallbacks = [];
                this._rejectCallbacks = [];
            }

            static isPromise(some) {
                return some && some.then && typeof some.then === 'function';
            }

        }

        return PromiseControl;
    };

    factory.$inject = [];

    angular.module('app.utils').factory('PromiseControl', factory);
})();


text:
from __future__ import print_function
from builtins import str
from builtins import range
import os
import sys
import numpy as np
from girs.feat.layers import LayersReader
from girs.rast.raster import RasterReader, RasterWriter, get_driver
from girs.rast.raster import get_parameters
from girs.rastfeat import rasterize

def clip_rasters(rasters, output_dir=None, suffix=''):
    """Clip a list of rasters

    :param rasters:
    :param output_dir:
    :param suffix:
    :return:
    """
    if not output_dir:
        output_dir = os.path.dirname(rasters[0])
    x_min = -sys.float_info.max
    x_max = sys.float_info.max
    y_min = -sys.float_info.max
    y_max = sys.float_info.max
    w_list = []
    h_list = []
    for r in rasters:
        parameters = get_parameters(r)
        w, h = parameters.pixel_size()
        w_list.append(w)
        h_list.append(h)
        x_min0, x_max0, y_min0, y_max0 = parameters.get_extent()
        x_min = max(x_min0, x_min)
        x_max = min(x_max0, x_max)
        y_min = max(y_min0, y_min)
        y_max = min(y_max0, y_max)
    assert w_list[1:] == w_list[:-1]
    assert h_list[1:] == h_list[:-1]
    x_min += w_list[0] / 2.0
    x_max -= w_list[0] / 2.0
    y_min += h_list[0] / 2.0
    y_max -= h_list[0] / 2.0
    output_filenames = []
    for r in rasters:
        f_out = os.path.basename(r).split('.')[0] + suffix + '.tif'
        f_out = os.path.join(output_dir, f_out)
        clip_by_extent(r, extent=[x_min, x_max, y_min, y_max], output_raster=f_out)
        output_filenames.append(f_out)
    return output_filenames

def clip_by_extent(raster_in, **kwargs):
    """Clip the raster by extent

    If `output_raster` is not set in kwargs, return the new rasters dataset as `MEM` driver, otherwise None

    :param raster_in:
    :param kwargs:
        :key extent: (list): [x_min, x_max, y_min, y_max] is the extent in world coordinates
        :key layers: (string / Layers): layers file name or LayersSet object used to get the extent
        :key rasters: (string / Layers): rasters file name or Raster object used to get the extent
        :key layer_number: (int): layer number, only used if `layers` is defined. Default is the first layer (0)
        :key scale: (float): scale the extent: scale > 1 creates a buffer
        :key driver: (string): driver short name
        :key output_raster: (string): filename of the rasters.
    :return:
    """
    try:
        raster_in = RasterReader(raster_in)
    except:
        pass

    try:
        raster_parameters = raster_in.get_parameters()
    except Exception:
        try:
            raster_parameters = get_parameters(raster_in)
        except Exception:
            raster_parameters = raster_in

    x_min0, x_max0, y_min0, y_max0 = raster_parameters.get_extent_world()

    if 'extent' in kwargs:
        x_min, x_max, y_min, y_max = kwargs['extent']
    elif 'layers' in kwargs:
        try:
            layers = LayersReader(kwargs['layers'])
        except (TypeError, RuntimeError):
            layers = kwargs['layers']
        layer_number = kwargs['layer_number'] if 'layer_number' in kwargs else 0
        layers = layers.transform(wkt=raster_in.get_coordinate_system())
        x_min, x_max, y_min, y_max = layers.get_extent(layer_number=layer_number)
    elif 'rasters' in kwargs:
        try:
            raster0 = RasterReader(kwargs['rasters'])
        except Exception as e:
            raster0 = kwargs['rasters']
        x_min, x_max, y_min, y_max = raster0.get_extent()
    else:
        x_min, x_max, y_min, y_max = x_min0, x_max0, y_min0, y_max0

    if 'scale' in kwargs:
        scale = kwargs['scale'] - 1.0
        d = max((x_max - x_min) * scale, (y_max - y_min) * scale)
        x_min -= d
        x_max += d
        y_min -= d
        y_max += d

    x_min = max(x_min, x_min0)
    x_max = min(x_max, x_max0)
    y_min = max(y_min, y_min0)
    y_max = min(y_max, y_max0)
    (u_min, u_max, v_min, v_max), geo_trans = raster_parameters.extent_world_to_pixel(x_min, x_max, y_min, y_max)
    u_min = max(u_min, 0)
    u_max = min(u_max, raster_parameters.RasterXSize - 1)
    v_min = max(v_min, 0)
    v_max = min(v_max, raster_parameters.RasterYSize - 1)
    raster_parameters.RasterXSize = u_max - u_min + 1
    raster_parameters.RasterYSize = v_max - v_min + 1
    raster_parameters.geo_trans = geo_trans

    if raster_parameters.RasterXSize < 0 or raster_parameters.RasterYSize < 0:
        msg = 'clip_by_extent: negative number of cells ({}, {}){}'
        if 'extent' in kwargs:
            msg1 = '\n\tThe parameter extent may be in a different coordinate system from raster:' + \
                   '\n\t\traster: {}\n\t\textent: {}'
            msg1 = msg1.format(str(raster_in.get_extent()), str(kwargs['extent']))
        else:
            msg1 = ''
        msg = msg.format(raster_parameters.RasterXSize,raster_parameters.RasterYSize, msg1)
        raise ValueError(msg)

    try:
        name = kwargs['output_raster']
        r_dir = os.path.dirname(name)
        if not os.path.isdir(r_dir):
            os.makedirs(r_dir)
    except Exception:
        name = ''

    try:
        driver = get_driver(driver_short_name=kwargs['driver'])
    except KeyError:
        driver = get_driver(name)

    raster_parameters.driverShortName = driver.ShortName

    raster_out = RasterWriter(raster_parameters, name)

    array = raster_in.get_array(band_number='all', col0=u_min, row0=v_min,
                                n_cols=raster_parameters.RasterXSize, n_rows=raster_parameters.RasterYSize)
    for i in range(raster_parameters.number_of_bands):
        r_band = raster_out.get_band(i+1)
        r_band.WriteArray(array[i])
    raster_out.dataset.FlushCache()
    return raster_out

def clip_by_vector(raster_in, layers_in, **kwargs):
        # layer_number=0, driver=None, burn_value=1, output_raster=None, nodata=None, all_touched=False):
    """Clip by vector

    :param raster_in:
    :type raster_in:
    :param layers_in: layers file name or Layers object. The geometry must be line or polygon
    :type layers_in:
    :param kwargs:
        :key layer_number: (int) layer number. Default is the first layer (0)
        :key scale: (float) scale the features' bounding box
        :key driver: driver name
        :key output_raster: filename of the rasters.
        :key nodata: nodata
        :key all_touched:
    :return: RasterWriter instance
    :rtype: RasterWriter
    """
    output_raster = kwargs.pop('output_raster', None)
    driver = get_driver(filename=output_raster, driver_short_name=kwargs.pop('driver', None))
    layer_number = kwargs.pop('layer_number', 0)
    nodata = kwargs.pop('nodata', None)

    all_touched = kwargs.pop('all_touched', False)

    try:
        layers_in = LayersReader(layers_in)
        layers_in.get_layer(layer_number)
    except (TypeError, RuntimeError):
        try:
            layers_in.get_layer(layer_number)
        except AttributeError:
            pass

    try:
        raster_in = RasterReader(raster_in)
    except AttributeError:
        pass

    srs_raster = raster_in.get_coordinate_system()
    if not srs_raster:
        print ('WARNING: raster {} has no coordinate system'.format(raster_in.get_rastername()) )
    else:
        layers_in = layers_in.transform(wkt=srs_raster)

    r_out = clip_by_extent(raster_in, extent=layers_in.get_extent(layer_number), driver='MEM')

    raster_parameters = r_out.get_parameters()
    raster_parameters.set_driver_short_name(driver.ShortName)
    array_out = r_out.get_array(band_number='all')
    del r_out

    if not nodata:
        nodata = raster_parameters.nodata

    burn_values = np.int32(1)  # TODO
    r_burn = rasterize.rasterize_layers(layers_in, burn_values=[burn_values], raster_parameters=raster_parameters,
                                        layer_number=layer_number, all_touched=all_touched)

    for i in range(0, raster_parameters.number_of_bands):
        array_burn = r_burn.get_array(i+1)
        array_mask = np.ma.masked_where(array_burn != burn_values, array_burn)
        b_nodata = nodata[i]
        array_out[i] = np.where(array_mask.mask, b_nodata, array_out[i])
    del r_burn

    raster_out = RasterWriter(raster_parameters, output_raster) #nu, nv, nb, data_types[0], geo_trans, srs, driver=driver, nodata=nodata)
    for i in range(raster_parameters.number_of_bands):
        raster_out.set_array(array_out[i], i+1)
    raster_out.dataset.FlushCache()
    return raster_out


text:
input[type="text"],
input[type="password"],
textarea,
textarea.form-control {
	height: 44px;
    margin: 0;
    padding: 0 20px;
    vertical-align: middle;
    background: #fff;
    border: 1px solid #ddd;
    font-family: 'Roboto', sans-serif;
    font-size: 16px;
    font-weight: 300;
    line-height: 44px;
    color: #888;
    -moz-border-radius: 4px; -webkit-border-radius: 4px; border-radius: 4px;
    -moz-box-shadow: none; -webkit-box-shadow: none; box-shadow: none;
    -o-transition: all .3s; -moz-transition: all .3s; -webkit-transition: all .3s; -ms-transition: all .3s; transition: all .3s;
}

textarea,
textarea.form-control {
	height: 90px;
	padding-top: 8px;
	padding-bottom: 8px;
	line-height: 30px;
}

input[type="text"]:focus,
input[type="password"]:focus,
textarea:focus,
textarea.form-control:focus {
	outline: 0;
	background: #fff;
    border: 1px solid #ccc;
    -moz-box-shadow: none; -webkit-box-shadow: none; box-shadow: none;
}

input[type="text"]:-moz-placeholder, input[type="password"]:-moz-placeholder,
textarea:-moz-placeholder, textarea.form-control:-moz-placeholder { color: #888; }

input[type="text"]:-ms-input-placeholder, input[type="password"]:-ms-input-placeholder,
textarea:-ms-input-placeholder, textarea.form-control:-ms-input-placeholder { color: #888; }

input[type="text"]::-webkit-input-placeholder, input[type="password"]::-webkit-input-placeholder,
textarea::-webkit-input-placeholder, textarea.form-control::-webkit-input-placeholder { color: #888; }

label { font-weight: 300; }

button.btn {
	min-width: 105px;
	height: 40px;
    margin: 0;
    padding: 0 20px;
    vertical-align: middle;
    border: 0;
    font-family: 'Roboto', sans-serif;
    font-size: 16px;
    font-weight: 300;
    line-height: 40px;
    color: #fff;
    -moz-border-radius: 4px; -webkit-border-radius: 4px; border-radius: 4px;
    text-shadow: none;
    -moz-box-shadow: none; -webkit-box-shadow: none; box-shadow: none;
    -o-transition: all .3s; -moz-transition: all .3s; -webkit-transition: all .3s; -ms-transition: all .3s; transition: all .3s;
}

button.btn:hover { opacity: 0.6; color: #fff; }
button.btn:active { outline: 0; opacity: 0.6; color: #fff; -moz-box-shadow: none; -webkit-box-shadow: none; box-shadow: none; }
button.btn:focus,
button.btn:active:focus,
button.btn.active:focus { outline: 0; opacity: 0.6; color: #fff; }

button.btn.btn-next,
button.btn.btn-next:focus,
button.btn.btn-next:active:focus, button.btn.btn-next.active:focus { background: #f35b3f; }

button.btn.btn-submit,
button.btn.btn-submit:focus,
button.btn.btn-submit:active:focus, button.btn.btn-submit.active:focus { background: #f35b3f; }

button.btn.btn-previous,
button.btn.btn-previous:focus,
button.btn.btn-previous:active:focus, button.btn.btn-previous.active:focus { background: #bbb; }


text:
@annotate: folktale.concurrency.task.rejected
category: Constructing
---

Constructs a Task that resolves with a rejected value.

The value is computed eagerly. If you need the value to be computed only when the task is ran you'll have to use the `task` function.

## Example::

    const { rejected } = require('folktale/concurrency/task');

    try {
      const result = await rejected('hello').run().promise();
      throw 'never happens';
    } catch (error) {
      $ASSERT(error == 'hello');
    }


text:
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE773_Missing_Reference_to_Active_File_Descriptor_or_Handle__fopen_22b.c
Label Definition File: CWE773_Missing_Reference_to_Active_File_Descriptor_or_Handle__fopen.label.xml
Template File: source-sinks-22b.tmpl.c
*/
/*
 * @description
 * CWE: 773 Missing Reference to Active File Descriptor or Handle
 * BadSource:  Create a file handle using fopen()
 * Sinks:
 *    GoodSink: Close the file handle before reusing it
 *    BadSink : Reassign the file handle before closing it
 * Flow Variant: 22 Control flow: Flow controlled by value of a global variable. Sink functions are in a separate file from sources.
 *
 * */

#include "std_testcase.h"

#ifndef OMITBAD

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

void CWE773_Missing_Reference_to_Active_File_Descriptor_or_Handle__fopen_22_badSink(FILE * data)
{
    if(CWE773_Missing_Reference_to_Active_File_Descriptor_or_Handle__fopen_22_badGlobal)
    {
        /* FLAW: Point data to another file handle without closing the handle from the source */
        data = fopen("BadSink_fopen.txt", "w+");
        /* avoid incidental for not closing the file handle */
        if (data != NULL)
        {
            fclose(data);
        }
    }
}

#endif /* OMITBAD */

#ifndef OMITGOOD

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

/* goodB2G1() - use badsource and goodsink by setting the static variable to false instead of true */
void CWE773_Missing_Reference_to_Active_File_Descriptor_or_Handle__fopen_22_goodB2G1Sink(FILE * data)
{
    if(CWE773_Missing_Reference_to_Active_File_Descriptor_or_Handle__fopen_22_goodB2G1Global)
    {
        /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */
        printLine("Benign, fixed string");
    }
    else
    {
        /* FIX: Close the file from the source before pointing data to a new file handle */
        if (data != NULL)
        {
            fclose(data);
        }
        data = fopen("GoodSink_fopen.txt", "w+");
        /* avoid incidental for not closing the file handle */
        if (data != NULL)
        {
            fclose(data);
        }
    }
}

/* goodB2G2() - use badsource and goodsink by reversing the blocks in the if in the sink function */
void CWE773_Missing_Reference_to_Active_File_Descriptor_or_Handle__fopen_22_goodB2G2Sink(FILE * data)
{
    if(CWE773_Missing_Reference_to_Active_File_Descriptor_or_Handle__fopen_22_goodB2G2Global)
    {
        /* FIX: Close the file from the source before pointing data to a new file handle */
        if (data != NULL)
        {
            fclose(data);
        }
        data = fopen("GoodSink_fopen.txt", "w+");
        /* avoid incidental for not closing the file handle */
        if (data != NULL)
        {
            fclose(data);
        }
    }
}

#endif /* OMITGOOD */


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

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.13"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<title>FPGA LIBrary: SyncClockDomains Entity  Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

<link href="search/search.css" rel="stylesheet" type="text/css"/>

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

FPGA LIBrary

Generics |
Ports |
Libraries |
Use Clauses

SyncClockDomains Entity Reference

Inheritance diagram for SyncClockDomains:

<map name="SyncClockDomains_inherit__map" id="SyncClockDomains_inherit__map">
<area shape="rect" id="node2" href="classSyncClockDomainsBase.html" title="SyncClockDomainsBase" alt="" coords="5,5,184,32"/>
</map>

Entities

Structural  	architecture

Libraries

IEEE

FPGALIB

Use Clauses

std_logic_1164

Sync 	   Package <Sync>

Generics

INBYLEVEL  	boolean  :=    FALSE

FFSTAGES  	natural  :=   2

CHANNELS  	positive  :=   1

Ports

rst_i  	 in  std_logic

clkA_i  	 in  std_logic

clkB_i  	 in  std_logic

a_i  	 in  std_logic_vector (    CHANNELS-  1  downto   0  )

b_o  	 out  std_logic_vector (    CHANNELS-  1  downto   0  )

ack_o  	 out  std_logic_vector (    CHANNELS-  1  downto   0  )

The documentation for this class was generated from the following file:

vhdl/sync/syncClockDomains.vhdl

<address class="footer">
Generated by

 1.8.13
</address>


text:
[//]: # "This README.md file is auto-generated, all changes to this file will be lost."
[//]: # "To regenerate it, use `python -m synthtool`."
<img src="https://avatars2.githubusercontent.com/u/2810941?v=3&s=96" alt="Google Cloud Platform logo" title="Google Cloud Platform" align="right" height="96" width="96"/>

# [Address Validation API: Node.js Client](https://github.com/googleapis/google-cloud-node)

[![release level](https://img.shields.io/badge/release%20level-beta-yellow.svg?style=flat)](https://cloud.google.com/terms/launch-stages)
[![npm version](https://img.shields.io/npm/v/@googlemaps/addressvalidation.svg)](https://www.npmjs.org/package/@googlemaps/addressvalidation)

 client for Node.js

A comprehensive list of changes in each version may be found in
[the CHANGELOG](https://github.com/googleapis/google-cloud-node/tree/main/packages/google-maps-addressvalidation/CHANGELOG.md).

* [Address Validation API Node.js Client API Reference][client-docs]
* [Address Validation API Documentation][product-docs]
* [github.com/googleapis/google-cloud-node/packages/google-maps-addressvalidation](https://github.com/googleapis/google-cloud-node/tree/main/packages/google-maps-addressvalidation)

Read more about the client libraries for Cloud APIs, including the older
Google APIs Client Libraries, in [Client Libraries Explained][explained].

[explained]: https://cloud.google.com/apis/docs/client-libraries-explained

**Table of contents:**

* [Quickstart](#quickstart)
  * [Before you begin](#before-you-begin)
  * [Installing the client library](#installing-the-client-library)
  * [Using the client library](#using-the-client-library)
* [Samples](#samples)
* [Versioning](#versioning)
* [Contributing](#contributing)
* [License](#license)

## Quickstart

### Before you begin

1.  [Select or create a Cloud Platform project][projects].
1.  [Enable billing for your project][billing].
1.  [Enable the Address Validation API API][enable_api].
1.  [Set up authentication with a service account][auth] so you can access the
    API from your local workstation.

### Installing the client library

```bash
npm install @googlemaps/addressvalidation
```

### Using the client library

```javascript
/**
 * This snippet has been automatically generated and should be regarded as a code template only.
 * It will require modifications to work.
 * It may require correct/in-range values for request initialization.
 * TODO(developer): Uncomment these variables before running the sample.
 */
/**
 *  Required. The address being validated. Unformatted addresses should be
 *  submitted via `address_lines` google.type.PostalAddress.address_lines.
 *  The total length of the fields in this input must not exceed 300
 *  characters.
 *  Supported regions can be found in the
 *  FAQ (https://developers.google.com/maps/documentation/address-validation/faq#which_regions_are_currently_supported).
 *  The language_code google.type.PostalAddress.language_code  value in the
 *  input address is reserved for future uses and is ignored today. The
 *  validated address result will be populated based on the preferred language
 *  for the given address, as identified by the system.
 *  The Address Validation API ignores the values in
 *  recipients google.type.PostalAddress.recipients  and
 *  organization google.type.PostalAddress.organization. Any values in those
 *  fields will be discarded and not returned. Please do not set them.
 */
// const address = {}
/**
 *  This field must be empty for the first address validation request. If
 *  more requests are necessary to fully validate a single address (for
 *  example if the changes the user makes after the initial validation need to
 *  be re-validated), then each followup request must populate this field with
 *  the
 *  response_id google.maps.addressvalidation.v1.ValidateAddressResponse.response_id
 *  from the very first response in the validation sequence.
 */
// const previousResponseId = 'abc123'
/**
 *  Enables USPS CASS compatible mode. This affects _only_ the
 *  google.maps.addressvalidation.v1.ValidationResult.usps_data  field of
 *  google.maps.addressvalidation.v1.ValidationResult. Note: for USPS CASS
 *  enabled requests for addresses in Puerto Rico, a
 *  google.type.PostalAddress.region_code  of the `address` must be provided
 *  as "PR", or an google.type.PostalAddress.administrative_area  of the
 *  `address` must be provided as "Puerto Rico" (case-insensitive) or "PR".
 *  It's recommended to use a componentized `address`, or alternatively specify
 *  at least two google.type.PostalAddress.address_lines  where the first line
 *  contains the street number and name and the second line contains the city,
 *  state, and zip code.
 */
// const enableUspsCass = true

// Imports the Addressvalidation library
const {AddressValidationClient} = require('@googlemaps/addressvalidation').v1;

// Instantiates a client
const addressvalidationClient = new AddressValidationClient();

async function callValidateAddress() {
  // Construct request
  const request = {
    address: {
      regionCode: 'US',
      addressLines: ['1600 Amphitheatre Pkwy', 'Mountain View CA 94040'],
    },
  };

  // Run request
  const response = await addressvalidationClient.validateAddress(request);
  console.log(response);
}

callValidateAddress();

```

## Samples

Samples are in the [`samples/`](https://github.com/googleapis/google-cloud-node/tree/main/samples) directory. Each sample's `README.md` has instructions for running its sample.

| Sample                      | Source Code                       | Try it |
| --------------------------- | --------------------------------- | ------ |
| Address_validation.provide_validation_feedback | [source code](https://github.com/googleapis/google-cloud-node/blob/main/packages/google-maps-addressvalidation/samples/generated/v1/address_validation.provide_validation_feedback.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/google-cloud-node&page=editor&open_in_editor=packages/google-maps-addressvalidation/samples/generated/v1/address_validation.provide_validation_feedback.js,samples/README.md) |
| Address_validation.validate_address | [source code](https://github.com/googleapis/google-cloud-node/blob/main/packages/google-maps-addressvalidation/samples/generated/v1/address_validation.validate_address.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/google-cloud-node&page=editor&open_in_editor=packages/google-maps-addressvalidation/samples/generated/v1/address_validation.validate_address.js,samples/README.md) |
| Quickstart | [source code](https://github.com/googleapis/google-cloud-node/blob/main/packages/google-maps-addressvalidation/samples/quickstart.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/google-cloud-node&page=editor&open_in_editor=packages/google-maps-addressvalidation/samples/quickstart.js,samples/README.md) |
| Quickstart | [source code](https://github.com/googleapis/google-cloud-node/blob/main/packages/google-maps-addressvalidation/samples/test/quickstart.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/google-cloud-node&page=editor&open_in_editor=packages/google-maps-addressvalidation/samples/test/quickstart.js,samples/README.md) |

The [Address Validation API Node.js Client API Reference][client-docs] documentation
also contains samples.

## Supported Node.js Versions

Our client libraries follow the [Node.js release schedule](https://nodejs.org/en/about/releases/).
Libraries are compatible with all current _active_ and _maintenance_ versions of
Node.js.
If you are using an end-of-life version of Node.js, we recommend that you update
as soon as possible to an actively supported LTS version.

Google's client libraries support legacy versions of Node.js runtimes on a
best-efforts basis with the following warnings:

* Legacy versions are not tested in continuous integration.
* Some security patches and features cannot be backported.
* Dependencies cannot be kept up-to-date.

Client libraries targeting some end-of-life versions of Node.js are available, and
can be installed through npm [dist-tags](https://docs.npmjs.com/cli/dist-tag).
The dist-tags follow the naming convention `legacy-(version)`.
For example, `npm install @googlemaps/addressvalidation@legacy-8` installs client libraries
for versions compatible with Node.js 8.

## Versioning

This library follows [Semantic Versioning](http://semver.org/).

This library is considered to be in **beta**. This means it is expected to be
mostly stable while we work toward a general availability release; however,
complete stability is not guaranteed. We will address issues and requests
against beta libraries with a high priority.

More Information: [Google Cloud Platform Launch Stages][launch_stages]

[launch_stages]: https://cloud.google.com/terms/launch-stages

## Contributing

Contributions welcome! See the [Contributing Guide](https://github.com/googleapis/google-cloud-node/blob/main/CONTRIBUTING.md).

Please note that this `README.md`, the `samples/README.md`,
and a variety of configuration files in this repository (including `.nycrc` and `tsconfig.json`)
are generated from a central template. To edit one of these files, make an edit
to its templates in
[directory](https://github.com/googleapis/synthtool).

## License

Apache Version 2.0

See [LICENSE](https://github.com/googleapis/google-cloud-node/blob/main/LICENSE)

[client-docs]: https://cloud.google.com/nodejs/docs/reference/addressvalidation/latest
[product-docs]: https://mapsplatform.google.com/maps-products/address-validation/
[shell_img]: https://gstatic.com/cloudssh/images/open-btn.png
[projects]: https://console.cloud.google.com/project
[billing]: https://support.google.com/cloud/answer/6293499#enable-billing
[enable_api]: https://console.cloud.google.com/flows/enableapi?apiid=addressvalidation.googleapis.com
[auth]: https://cloud.google.com/docs/authentication/getting-started


text:
package com.wxs.exception.controller;

import com.wxs.exception.common.Result;
import com.wxs.exception.common.ResultCode;
import com.wxs.exception.common.exception.ApiException;
import com.wxs.exception.common.exception.OrderNotFoundException;
import com.wxs.exception.service.impl.LoginServiceImpl;
import com.wxs.exception.vo.VerifyInfo;
import com.wxs.exception.vo.VerifyPass;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.NotNull;

import static org.springframework.web.bind.annotation.RequestMethod.GET;

@RestController
@RequestMapping("/login")
@Api(value = "/login", tags = "用户登录接口")
@Slf4j
public class LoginController {

    @Autowired
    private LoginServiceImpl loginService;

    @PostMapping("/verify")
    @ApiOperation(value = "校验", notes = "校验")
    @ApiResponses(value = {@ApiResponse(code = 400, message = "Invalid tag value")})
    public Result verifyLogin(VerifyPass verifyPass) {
        Result<VerifyInfo> result = new Result<>();
        try {
            VerifyInfo verifyInfo;
            verifyInfo = loginService.verify(verifyPass.getUsername(), verifyPass.getPass());
            if (null == verifyInfo) {
                result.doErrorHandle("当前用户不存在");
            }
            result.setData(verifyInfo);
            return result;
        } catch (Exception e) {
            result.doErrorHandle("当前用户不存在");
            return result;
        }
    }

    @GetMapping("/test")
    @ApiOperation(value = "测试接口", notes = "测试接口")
    public Result test() {
        log.info("/login/test------------");
        loginService.testApiException();
        return new Result(ResultCode.SUCCESS);
    }

    @RequestMapping(value="/orders/{id}", method=GET)
    public String showOrder(@PathVariable("id") long id, @NotNull VerifyPass verifyPass, Model model) {
        VerifyInfo  verifyInfo = loginService.testOrderNotFoundException(verifyPass.getUsername(), verifyPass.getPass());

        if (verifyInfo == null) {
            throw new OrderNotFoundException(id);
        }

        model.addAttribute(verifyInfo);
        return "orderDetail";
    }
}


text:
using System.Runtime.CompilerServices;
using Xrm.Sdk;

public partial class ActivityPointer : Entity
{

    /// <summary>
    /// Default Constructor.
    /// </summary>
    public ActivityPointer() :
        base(EntityLogicalName)
    {
    }

    public const string EntityLogicalName = "activitypointer";

    public const int EntityTypeCode = 4200;

    [ScriptName("activityid")]
    public string activityid;

    /// <summary>
    /// The name of the custom entity.
    /// </summary>
    [ScriptName("subject")]
    public string subject ;

    [ScriptName("activitytypecode")]
    public string ActivityTypeCode;

    [ScriptName("regardingobjectid")]
    public EntityReference RegardingObjectId;

    public string DisplaySubject;

    internal void UpdateCalculatedFields()
    {
        LogicalName = ActivityTypeCode;

    }
}

public enum dev1_session_StatusCode
{
    Draft =1
}
public partial class dev1_session :Entity
{
    /// <summary>
    /// Default Constructor.
    /// </summary>
    public dev1_session() :
        base(EntityLogicalName)
    {
        this._metaData["dev1_duration"] = AttributeTypes.Int_;

    }

    public const string EntityLogicalName = "dev1_session";
    public const int EntityTypeCode = 10000;

    /// <summary>
    /// Date and time when the record was created.
    /// </summary>
    [ScriptName("createdon")]
    public DateTime CreatedOn;

    /// <summary>
    /// The name of the custom entity.
    /// </summary>
    [ScriptName("dev1_description")]
    public string dev1_Description;

    /// <summary>
    ///
    /// </summary>
    [ScriptName("dev1_duration")]
    public int? dev1_Duration;

    [ScriptName("dev1_activityid")]
    public string dev1_ActivityId;

    [ScriptName("dev1_activitytypename")]
    public string dev1_ActivityTypeName;

    /// <summary>
    /// Unique identifier for E-mail associated with Session.
    /// </summary>
    [ScriptName("dev1_emailid")]
    public EntityReference dev1_EmailId;

    [ScriptName("dev1_phonecallid")]
    public EntityReference dev1_PhoneCallId;

    /// <summary>
    /// Unique identifier for Letter associated with Session.
    /// </summary>
    [ScriptName("dev1_letterid")]
    public EntityReference dev1_LetterId;

    /// <summary>
    /// Unique identifier for Task associated with Session.
    /// </summary>
    [ScriptName("dev1_taskid")]
    public EntityReference dev1_TaskId;

    /// <summary>
    ///
    /// </summary>
    [ScriptName("dev1_endtime")]
    public DateTime dev1_EndTime;

    [ScriptName("dev1_row")]
    public int? dev1_Row;

    [ScriptName("statuscode")]
    public OptionSetValue StatusCode;

    /// <summary>
    /// Unique identifier for entity instances
    /// </summary>
    [ScriptName("dev1_sessionid")]
    public Guid dev1_sessionId;

    /// <summary>
    ///
    /// </summary>
    [ScriptName("dev1_starttime")]
    public DateTime dev1_StartTime = null;

    [ScriptName("contract_customerid")]
    public EntityReference contract_customerid = null;

    [ScriptName("incident_customerid")]
    public EntityReference incident_customerid = null;

    [ScriptName("opportunity_customerid")]
    public EntityReference opportunity_customerid = null;

    [ScriptName("activitypointer_regardingobjectid")]
    public EntityReference activitypointer_regardingobjectid = null;

    [ScriptName("activitypointer_subject")]
    public string activitypointer_subject;
    /// <summary>
    /// This is a virtual field that stores the account as defined when filtering activities
    /// and then when retrieved it is set from the regarding entity customer id field
    /// </summary>
    [ScriptName("account")]
    public EntityReference Account;

}


text:
var q = require('q'),
  inquirer = require('inquirer'),
  fs = require('fs'),
  path = require('path'),
  colors = require('colors'),
  init = require('../init'),
  fileHelper = require('../fileHelper'),
  scriptHelper = require('../scriptHelper'),
  namer = require('../namer'),
  log = require('../log');

function prompt() {
  var deferred = q.defer();
  inquirer.prompt([
    {
      type: 'confirm',
      name: 'useHtml',
      message: 'Do you want a template html and css?',
      default: true
    }
  ], function (answers) {
    deferred.resolve(answers.useHtml);
  });
  return deferred.promise;
}

module.exports = function (name) {
  var options, directiveType;

  var values = {
    name: namer.directive(name),
    filename: namer.file(namer.directive(name))
  };

  log.info('Creating directive: ' + name.cyan);

  return prompt()
    .then(function (_useHtml) {
      directiveType = _useHtml ? 'element' : 'attribute';
      return init.load();
    })
    .then(function (_options) {
      options = _options;
      values.module = options.module;
      return fileHelper.getTemplates('directive', values);
    })
    .then(function (templates) {
      return templates.reduce(function (map, tmpl) {
        map[tmpl.name] = tmpl;
        return map;
      }, {});
    })
    .then(function (tmplMap) {
      var files = [];

      if(directiveType === 'element') {

        // code file
        files.push(fileHelper.saveFile(
          path.resolve(process.cwd(),
            options.sourceFolder,
            'directives',
            values.name,
            values.filename + '.js'),
          tmplMap['template-element.js'].content));

        // html file
        files.push(fileHelper.saveFile(
          path.resolve(process.cwd(),
            options.sourceFolder,
            'directives',
            values.name,
            values.filename + '.html'),
          tmplMap['template.html'].content));

        // css file
        files.push(fileHelper.saveFile(
          path.resolve(process.cwd(),
            options.sourceFolder,
            'directives',
            values.name,
            values.filename + '.' + options.cssPrecompiler),
          ''));

        // test file
        files.push(fileHelper.saveFile(
          path.resolve(process.cwd(),
            options.testFolder,
            'unit',
            'directives',
            values.filename + '.js'),
          tmplMap['test-element.js'].content));
      } else {
        // code file
        files.push(fileHelper.saveFile(
          path.resolve(process.cwd(),
            options.sourceFolder,
            'directives',
            values.filename + '.js'),
          tmplMap['template-attribute.js'].content));

        // test file
        files.push(fileHelper.saveFile(
          path.resolve(process.cwd(),
            options.testFolder,
            'unit',
            'directives',
            values.filename + '.js'),
          tmplMap['test-attribute.js'].content));
      }

      return q.all(files);
    })
    .then(function () {
      var codePath = (directiveType === 'element') ? 'directives/' + values.name : 'directives';
      return scriptHelper.insertScripts({
        name: values.filename,
        type: 'directive',
        codePath: codePath,
        testPath: 'directives'
      });
    })
    .then(function () {
      if('element' === directiveType) {
        return scriptHelper.insertImport(options.sourceFolder + '/directives/' + values.name + '/' + values.name + '/');
      } else {
        return;
      }
    });
};


text:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title data-i18n="resources.title_vectorTileLayerNormal"></title>


text: mvn exec:java -Dexec.args="%*"