text:
@implementation MyScene

@end

redpajama_set_name: RedPajamaGithub


text:
import * as transit from 'transit-js'
import { List, Map } from 'immutable'

// See: https://github.com/cognitect/transit-js/wiki/Getting-Started#default-write-handlers

const defaultWriteHandler = transit.makeWriteHandler({
  tag (v) {
    return typeof v.tag === 'function'
      ? v.tag()
      : new Error('tag method not implemented on ' + v)
  },
  rep (v) {
    return typeof v.rep === 'function'
      ? v.rep()
      : new Error('rep method not implementd on ' + v)
  },
  stringRep () { return null }
})

// See: https://github.com/cognitect/transit-js/wiki/Getting-Started#customizing-map--array-encoding

const immutableListWriteHandler = transit.makeWriteHandler({
  tag () { return 'array' },
  rep (v) { return v },
  stringRep () { return null }
})

const immutableMapWriteHandler = transit.makeWriteHandler({
  tag () { return 'map' },
  rep (v) { return v },
  stringRep () { return null }
})

export default {
  handlers: transit.map([
    'default', defaultWriteHandler,
    List, immutableListWriteHandler,
    Map, immutableMapWriteHandler
  ])
}


text:
/**
 * Jakarta Bean Validation TCK
 *
 * License: Apache License, Version 2.0
 * See the license.txt file in the root directory or <http://www.apache.org/licenses/LICENSE-2.0>.
 */
package org.hibernate.beanvalidation.tck.tests.valueextraction.builtin;

import jakarta.validation.valueextraction.ValueExtractor;

import org.hibernate.beanvalidation.tck.beanvalidation.Sections;
import org.hibernate.beanvalidation.tck.javafx.JavaFXValueExtractorsTestImpl;
import org.hibernate.beanvalidation.tck.tests.AbstractTCKTest;
import org.hibernate.beanvalidation.tck.util.JavaFXTest;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.jboss.test.audit.annotations.SpecAssertion;
import org.jboss.test.audit.annotations.SpecVersion;
import org.testng.annotations.Test;

/**
 * Tests for JavaFX {@link ValueExtractor}s.
 * <p>
 * The content of the tests is externalized in {@link JavaFXValueExtractorsTestImpl} to avoid a JavaFX dependency.
 *
 * @author Khalid Alqinyah
 * @author Hardy Ferentschik
 * @author Guillaume Smet
 *
 * @see JavaFXValueExtractorsTestImpl
 */
@JavaFXTest
@SpecVersion(spec = "beanvalidation", version = "3.0.0")
public class JavaFXValueExtractorsTest extends AbstractTCKTest {

	@Deployment
	public static WebArchive createTestArchive() {
		return webArchiveBuilder()
				.withTestClass( JavaFXValueExtractorsTest.class )
				.withClass( JavaFXValueExtractorsTestImpl.class )
				.build();
	}

	@Test
	@SpecAssertion(section = Sections.VALUEEXTRACTORDEFINITION_BUILTINVALUEEXTRACTORS, id = "f")
	public void testJavaFXBasicProperties() {
		JavaFXValueExtractorsTestImpl.testJavaFXBasicProperties();
	}

	@Test
	@SpecAssertion(section = Sections.VALUEEXTRACTORDEFINITION_BUILTINVALUEEXTRACTORS, id = "g")
	public void testValueExtractionForPropertyList() {
		JavaFXValueExtractorsTestImpl.testValueExtractionForPropertyList();
	}

	@Test
	@SpecAssertion(section = Sections.VALUEEXTRACTORDEFINITION_BUILTINVALUEEXTRACTORS, id = "h")
	public void testValueExtractionForPropertySet() {
		JavaFXValueExtractorsTestImpl.testValueExtractionForPropertySet();
	}

	@Test
	@SpecAssertion(section = Sections.VALUEEXTRACTORDEFINITION_BUILTINVALUEEXTRACTORS, id = "i")
	public void testValueExtractionForPropertyMap() {
		JavaFXValueExtractorsTestImpl.testValueExtractionForPropertyMap();
	}

	@Test
	@SpecAssertion(section = Sections.VALUEEXTRACTORDEFINITION_BUILTINVALUEEXTRACTORS, id = "g")
	@SpecAssertion(section = Sections.VALUEEXTRACTORDEFINITION_BUILTINVALUEEXTRACTORS, id = "f")
	@SpecAssertion(section = Sections.CONSTRAINTDECLARATIONVALIDATIONPROCESS_CONTAINERELEMENTCONSTRAINTS, id = "f")
	public void testValueExtractionForListOfStringProperty() {
		JavaFXValueExtractorsTestImpl.testValueExtractionForListOfStringProperty();
	}
}


text:
package unit

type ErrorSubject struct {
	*Subject
	value error
}

func NewErrorSubject(base *Subject, value error) *ErrorSubject {
	subject := new(ErrorSubject)
	subject.Subject = base
	subject.value = value
	return subject
}

func (subject *ErrorSubject) Named(name string) *ErrorSubject {
	subject.Subject.Named(name)
	return subject
}

func (subject *ErrorSubject) Fail(verb string, other error) {
	subject.FailWithMessage("Not true that " + subject.DisplayString() + " " + verb + " <" + other.Error() + ">.")
}

func (subject *ErrorSubject) DisplayString() string {
	return subject.Subject.DisplayString(subject.value.Error())
}

func (subject *ErrorSubject) Equals(expectation error) {
	if subject.value != expectation {
		subject.Fail("is equal to", expectation)
	}
}

func (subject *ErrorSubject) IsNil() {
	if subject.value != nil {
		subject.FailWithMessage("Not true that " + subject.DisplayString() + " is nil.")
	}
}


text:
package com.simpleerp.adapters;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.simpleerp.Control.SimpleControl;
import com.simpleerp.MenuPrincipal;
import com.simpleerp.R;
import com.simpleerp.entidades.Insumo;
import com.simpleerp.entidades.Produto;

import java.util.List;
import java.util.Map;

/**
 * Created by CharlleNot on 19/10/2015.
 */

public class ProdutoAdapter extends BaseAdapter {
    private List<Produto> lProduto;
    private Context context;
    private SimpleControl sistema;
    private TextView tvQtd;
    private ImageView imgCusto;
    private ImageView imgInsumos;
    private TextView tvCust;
    private TextView tvPreco;
    private ImageView imgPreco;

    public ProdutoAdapter(Context context, List<Produto> lProduto){
        this.context = context;
       this.lProduto=lProduto;
        sistema= MenuPrincipal.sistema;
    }

    @Override
    public int getCount() {
        return lProduto.size();
    }

    @Override
    public Produto getItem(int position) {
        return this.lProduto.get(position);
    }

    @Override
    public long getItemId(int position) {
        return this.lProduto.get(position).getId();
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        Produto produto= lProduto.get(position);

        LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View layout =inflater.inflate(R.layout.adapter_produto_producao, null);

        TextView tvNome = (TextView) layout.findViewById(R.id.textViewNomeProduto);
        tvNome.setText(produto.getNome());
        ImageView addMarca = (ImageView)layout.findViewById(R.id.addMarca);

        tvPreco = (TextView) layout.findViewById(R.id.textViewPreco);
        imgCusto = (ImageView)layout.findViewById(R.id.imageView14);
        imgInsumos = (ImageView)layout.findViewById(R.id.imageView15);
        imgPreco = (ImageView)layout.findViewById(R.id.ivPreco);

        tvQtd = (TextView) layout.findViewById(R.id.textViewQtdInsumo);
        tvCust = (TextView) layout.findViewById(R.id.textViewCusto);

        if(context.getClass().getSimpleName().equalsIgnoreCase("MenuPrincipal")){
            alterVisibility(View.VISIBLE);
            addMarca.setVisibility(View.GONE);
            tvPreco.setText(" R$ " + produto.getPreco());
            try {
                List<Insumo> list=sistema.getInsumosProduto(produto);
                Map<Long,List<String>>relacaoTemp=sistema.getRelacaoTemp(produto);
                if(list.size()>0){
                    tvQtd.setText(""+list.size());
                    float custo=0;
                    for(Insumo i : list){
                        float x=Float.parseFloat(relacaoTemp.get(i.getId()).get(1));
                        if(i.getTipo().equalsIgnoreCase(relacaoTemp.get(i.getId()).get(0))){
                            if(x>i.getQuantidade()){
                                custo=custo+((x/i.getQuantidade())*i.getCustoUnidade());
                            }else if(x==i.getCustoUnidade()) {
                                custo=custo+i.getCustoUnidade();
                            }else{
                                float temp = (i.getCustoUnidade()/i.getQuantidade());
                                custo=custo+(temp*x);
                            }
                        }else{
                            if(i.getTipo().equalsIgnoreCase("Quilos")){
                                float tempQuant=i.getQuantidade()*1000;
                                float temp = (i.getCustoUnidade()/tempQuant);
                                custo=custo+(temp*x);
                            }else{
                                float tempQuant=i.getQuantidade()/1000;
                                custo=custo+((x/tempQuant)*i.getCustoUnidade());
                            }

                        }
                    }
                    tvCust.setText(""+custo);

                }else{
                    tvCust.setText("0");
                    tvQtd.setText("0");
                }

            } catch (Exception e){

            }

        }else{
            alterVisibility(View.GONE);
            addMarca.setVisibility(View.VISIBLE);
            if(produto.isAddList()==true){
                addMarca.setBackgroundResource(R.drawable.ok);
            }else{
                addMarca.setBackgroundResource(android.R.drawable.ic_input_add);
            }

        }

        return layout;
    }
    private void alterVisibility(int visibility){
        tvPreco.setVisibility(visibility);
        tvCust.setVisibility(visibility);
        tvQtd.setVisibility(visibility);
        imgCusto.setVisibility(visibility);
        imgInsumos.setVisibility(visibility);
        imgPreco.setVisibility(visibility);
    }

}


text:
using System;
using System.IO;
using ipp;
using MHApi.DrewsClasses;
using MHApi.Imaging;
using MHApi.Laser;
using MHApi.Scanning;
using ZebraTrack.ViewModels;

namespace ZebraTrack.Experiments
{

    /// <summary>
    /// Open loop paradigm presenting an increasing power ramp followed by a decreasing power ramp
    /// to larval zebrafish. Up/down ramps occur back-to-back and are interleaved with resting phases
    /// </summary>
    unsafe class OpenLoopLaserRamp : TrackingExperiment
    {
        public enum ExperimentPhase { Habituation=0, RampUp=1, RampDown=2, Rest=3, Done=4};

        #region Members

        /// <summary>
        /// The last frame that was processed
        /// </summary>
        int _lastFrame = 0;

        /// <summary>
        /// The file writer to save experiment information
        /// </summary>
        StreamWriter _trackWriter;

        /// <summary>
        /// Writes fish region camera image
        /// </summary>
        TiffWriter _imageWriter;

        /// <summary>
        /// Writes fish region background image
        /// </summary>
        TiffWriter _backgroundWriter;

        /// <summary>
        /// Image for region around fish
        /// </summary>
        Image8 _camRegion;

        /// <summary>
        /// Our laser power controller
        /// </summary>
        SDLPS500Controller _laser;

        /// <summary>
        /// Scanner to acquire fish images
        /// </summary>
        RandomAccessScanner _scanner;

        /// <summary>
        /// The current experiment phase
        /// </summary>
        ExperimentPhase _experimentPhase;

        /// <summary>
        /// Laser power at the start of the heating ramp and during resting
        /// </summary>
        double _baseLaserPower;

        /// <summary>
        /// Laser power at the end of the heating ramp
        /// </summary>
        double _peakLaserPower;

        /// <summary>
        /// The total number of habituation frames
        /// </summary>
        int _habitFrames;

        /// <summary>
        /// The total number of rest phase frames
        /// </summary>
        int _restFrames;

        /// <summary>
        /// The total number of frames ramping up or down
        /// </summary>
        int _rampFrames;

        /// <summary>
        /// The number of trials
        /// </summary>
        int _nTrials;

        /// <summary>
        /// The frame number within the current phase
        /// </summary>
        int _currentPhaseFrame;

        /// <summary>
        /// The currently active trial
        /// </summary>
        int _currentTrial;

        #endregion

        public OpenLoopLaserRamp(int habitSeconds, int rampSeconds, int restSeconds, int nTrials, int frameRate, int pxPERmm, string folder, string name, string fishID) :
            base(folder, name, fishID, habitSeconds + (rampSeconds*2+restSeconds)*nTrials, frameRate, pxPERmm)
        {
            if (FileSaver != null)
            {
                _trackWriter = FileSaver.GetStreamWriter(".track");
                _imageWriter = FileSaver.GetTiffWriter("_camImage.tif", true);
                _backgroundWriter = FileSaver.GetTiffWriter("_bgImage.tif", true);
                //Create 10x10 mm region image
                _camRegion = new Image8(Properties.Settings.Default.PixelsPermm * 10, Properties.Settings.Default.PixelsPermm * 10);
            }
            _laser = new SDLPS500Controller(Properties.Settings.Default.DAQ, Properties.Settings.Default.LaserAO);
            string xchannel = Properties.Settings.Default.DAQ + "/" + Properties.Settings.Default.ScannerX;
            string ychannel = Properties.Settings.Default.DAQ + "/" + Properties.Settings.Default.ScannerY;
            //Load scan lookup table from file
            try
            {
                TextReader reader = File.OpenText("main.calib");
                var scanTable = BLIScanLookupTable.LoadFromFile(reader);
                _scanner = new RandomAccessScanner(scanTable, xchannel, ychannel, -10, 10);
                reader.Dispose();
            }
            catch (IOException)
            {
                System.Diagnostics.Debug.WriteLine("Could not find calibration data. No targeting available");
            }
            _habitFrames = habitSeconds * FrameRate;
            _restFrames = restSeconds * FrameRate;
            _rampFrames = rampSeconds * FrameRate;
            _nTrials = nTrials;
            _currentPhaseFrame = 0;
            _currentTrial = 0;//Start at 0 during habituation - will be pre-incremented as we enter ramp up phase and checked for completing at end of rest phase
            //This is a closed-loop experiment - try to stay fully up-to-date
            SuggestedBufferSeconds = 0;
            //Start in habituation phase
            _experimentPhase = ExperimentPhase.Habituation;
        }

        #region Properties

        /// <summary>
        /// Laser power at the start of the heating ramp and during resting
        /// </summary>
        public double BaseLaserPower
        {
            get
            {
                return _baseLaserPower;
            }
            set
            {
                if (value >= 0 && value <= 8000)
                    _baseLaserPower = value;
                else
                    throw new ArgumentOutOfRangeException(nameof(BaseLaserPower), "Laser power has to be between 0 and 8000 mW");
            }
        }

        /// <summary>
        /// Laser power at the end of the heating ramp
        /// </summary>
        public double PeakLaserPower
        {
            get
            {
                return _peakLaserPower;
            }
            set
            {
                if (value >= 0 && value <= 8000)
                    _peakLaserPower = value;
                else
                    throw new ArgumentOutOfRangeException(nameof(PeakLaserPower), "Laser power has to be between 0 and 8000 mW");
            }
        }

        public override string StatusMessage
        {
            get
            {
                switch (_experimentPhase)
                {
                    case ExperimentPhase.Habituation:
                        return "Habituation Phase";
                    case ExperimentPhase.RampUp:
                        return "Heating Ramp";
                    case ExperimentPhase.RampDown:
                        return "Cooling Ramp";
                    case ExperimentPhase.Rest:
                        return "Rest phase";
                }
                return "Done";
            }
        }

        /// <summary>
        /// The number of seconds remaining in the experiment
        /// </summary>
        public override int SecondsRemaining
        {
            get
            {
                return (ExperimentLength - _lastFrame / FrameRate);
            }
        }

        #endregion

        #region Methods

        /// <summary>
        /// Write pertinent information to info file
        /// </summary>
        /// <param name="infoWriter">The stream writer of the info file</param>
        protected override void WriteExperimentInfo(StreamWriter infoWriter)
        {
            base.WriteExperimentInfo(infoWriter);
            infoWriter.WriteLine();
            infoWriter.WriteLine("Power ramp experiment");
            infoWriter.WriteLine("Habituation length {0} [s]", _habitFrames / FrameRate);
            infoWriter.WriteLine("Ramp length {0} [s]", _rampFrames / FrameRate);
            infoWriter.WriteLine("Rest length {0} [s]", _restFrames / FrameRate);
            infoWriter.WriteLine("Base power {0} [mW]", BaseLaserPower);
            infoWriter.WriteLine("Peak power {0} [mW]", PeakLaserPower);
            infoWriter.WriteLine();
        }

        /// <summary>
        /// Write information to track file
        /// </summary>
        /// <param name="fish"></param>
        private void WriteTrackInfo(int frameNumber, BlobWithMoments fish)
        {
            if (fish != null)
            {
                _trackWriter.WriteLine("{0}\t{1}\t{2}\t{3}\t{4}\t{5}\t{6}", frameNumber, fish.Centroid.x, fish.Centroid.y, fish.Angle, (int)_experimentPhase, _currentTrial, _laser.LaserPower);
            }
            else
            {
                _trackWriter.WriteLine("NaN\tNaN\tNaN\tNaN\t{0}\t{1}\tNaN", (int)_experimentPhase, _currentTrial);
            }
        }

        /// <summary>
        /// Switches phase to ramp-up marking the begin of a new trial
        /// </summary>
        private void SwitchToRampUp()
        {
            _experimentPhase = ExperimentPhase.RampUp;
            _currentPhaseFrame = 0;
            _currentTrial++;
        }

        /// <summary>
        /// Processes one frame during habituation
        /// </summary>
        private void RunHabituation()
        {
            //Here we simply count down the clock and then move to ramp up phase
            if (_currentPhaseFrame >= _habitFrames)
            {
                SwitchToRampUp();
            }
            else
                _currentPhaseFrame++;
        }

        /// <summary>
        /// Processes one frame during RampUp
        /// </summary>
        private void RunRampUp()
        {
            //compute laser power as linear ramp over phase
            _laser.LaserPower = ((double)_currentPhaseFrame / (double)_rampFrames) * (PeakLaserPower - BaseLaserPower) + BaseLaserPower;
            if (_currentPhaseFrame >= _rampFrames)
            {
                _currentPhaseFrame = 0;
                _experimentPhase = ExperimentPhase.RampDown;
            }
            else
                _currentPhaseFrame++;
        }

        /// <summary>
        /// Processes one frame during RampDown
        /// </summary>
        private void RunRampDown()
        {
            //compute laser power as linear ramp over phase
            _laser.LaserPower = (1 - (double)_currentPhaseFrame / (double)_rampFrames) * (PeakLaserPower - BaseLaserPower) + BaseLaserPower;
            if (_currentPhaseFrame >= _rampFrames)
            {
                _currentPhaseFrame = 0;
                _experimentPhase = ExperimentPhase.Rest;
            }
            else
                _currentPhaseFrame++;
        }

        /// <summary>
        /// Processes one frame during Rest
        /// </summary>
        private void RunRest()
        {
            _laser.LaserPower = BaseLaserPower;
            if (_currentPhaseFrame >= _restFrames)
            {
                if(_currentTrial < _nTrials)
                    SwitchToRampUp();
                else
                {
                    _laser.LaserPower = 0;
                    _experimentPhase = ExperimentPhase.Done;
                }
            }
            else
                _currentPhaseFrame++;
        }

        /// <summary>
        /// Process the next frame
        /// </summary>
        /// <param name="frameNumber">The frame index</param>
        /// <param name="camImage">The camera image</param>
        /// <param name="poi">The fish location</param>
        /// <returns>Whether experiment should continue or not</returns>
        public override bool ProcessNext(int frameNumber, Image8 camImage, out IppiPoint? poi)
        {
            base.ProcessNext(frameNumber, camImage, out poi);
            _lastFrame = frameNumber;
            if (_scanner == null)
            {
                System.Diagnostics.Debug.WriteLine("Scanner was not initialized. Terminating experiment");
                return false;
            }
            if (_experimentPhase == ExperimentPhase.Done)
                return false;

            BlobWithMoments fish = null;
            fish = Tracker.Track(camImage);
            if (fish != null)
            {
                poi = new IppiPoint(fish.Centroid.x, fish.Centroid.y);
                try
                {
                    if (_scanner != null)
                        _scanner.Hit(poi.GetValueOrDefault());
                }
                catch (ArgumentOutOfRangeException)
                {
                    System.Diagnostics.Debug.WriteLine("Tried to hit coordinates outside scan table area.");
                    System.Diagnostics.Debug.WriteLine("Coordinates were: x={0}, y={1}", fish.xc, fish.yc);
                    System.Diagnostics.Debug.WriteLine("Terminating Experiment");
                    _laser.LaserPower = 0;
                    return false;
                }
            }
            //Write track information including current phase, current laser power
            WriteTrackInfo(frameNumber, fish);
            //Write images
            ip.ippiSet_8u_C1R(0, _camRegion.Image, _camRegion.Stride, _camRegion.Size);
            if(fish != null)
                MainViewModel.CopyRegionImage(fish.Centroid, _camRegion, camImage);
            _imageWriter.WriteFrame(_camRegion);
            if (fish != null)
                MainViewModel.CopyRegionImage(fish.Centroid, _camRegion, Tracker.Background);
            _backgroundWriter.WriteFrame(_camRegion);
            //Depending on phase call process method to control laser power and switch phase if appropriate
            switch (_experimentPhase)
            {
                case ExperimentPhase.Habituation:
                    RunHabituation();
                    break;
                case ExperimentPhase.RampUp:
                    RunRampUp();
                    break;
                case ExperimentPhase.RampDown:
                    RunRampDown();
                    break;
                case ExperimentPhase.Rest:
                    RunRest();
                    break;
            }
            //If we have lost the fish, disengage the laser
            if (fish == null)
                _laser.LaserPower = 0;
            return true;
        }

        protected override void Dispose(bool disposing)
        {
            base.Dispose(disposing);
            if (disposing)
            {
                if (_trackWriter != null)
                {
                    _trackWriter.Dispose();
                    _trackWriter = null;

                }
                if(_imageWriter != null)
                {
                    _imageWriter.Dispose();
                    _imageWriter = null;
                }
                if(_backgroundWriter != null)
                {
                    _backgroundWriter.Dispose();
                    _backgroundWriter = null;
                }
                if(_laser != null)
                {
                    _laser.Dispose();
                }
                if(_scanner != null)
                {
                    _scanner.Dispose();
                }
                if(_camRegion != null)
                {
                    _camRegion.Dispose();
                    _camRegion = null;
                }
            }
        }

        #endregion
    }
}


text:
Hello! We hope you're staying safe and healthy. Here's what you can find in this Postman release:

### What's New
* We've added support for an additional language when generating code snippets: You can now generate code snippets for Axios, to use in both the browser and node.js
[#135](https://github.com/postmanlabs/postman-code-generators/issues/135),
[#3822](https://github.com/postmanlabs/postman-app-support/issues/3822)

### Improvements
* Navigating between tabs should be smoother and snappier now that it won't be impacted by syncing
[#5609](https://github.com/postmanlabs/postman-app-support/issues/5609)
* When managing OAuth 2.0 tokens, you now have the options to delete all or just the expired tokens
[#6115](https://github.com/postmanlabs/postman-app-support/issues/6115)
* When working on a request body, you can now use autocomplete to insert variables more quickly and accurately
[#3517](https://github.com/postmanlabs/postman-app-support/issues/3517)
* When working with Postman variables in a JSON request body, there's now better support for syntax highlighting and formatting.
* When bringing Postman online, open API tabs will now update without going into a loading state.

### Bug Fixes
* Fixed a bug when generating code where custom headers would go missing
[#8550](https://github.com/postmanlabs/postman-app-support/issues/8550)

* Fixed an issue when starting the Postman snap app on the Wayland environment, where the app wouldn't open
[#6252](https://github.com/postmanlabs/postman-app-support/issues/6252)

* Fixed a bug when restarting the app, where tab titles for deleted requests would show [CONFLICT] instead of [DELETED]
[#7233](https://github.com/postmanlabs/postman-app-support/issues/7233)

* Fixed a bug when formatting JSON in request body, that would modify long numbers and numbers with decimals.
[#5658](https://github.com/postmanlabs/postman-app-support/issues/5658)

* Fixed a bug when validating JSON syntax where numbers beginning with zero were not highlighted as a validation error
[#7987](https://github.com/postmanlabs/postman-app-support/issues/7987)

* Fixed a bug when editing a JSON file that mistook closed brackets for Postman variables
[#7709](https://github.com/postmanlabs/postman-app-support/issues/7709)

* Fixed a bug in the raw body editor where unclosed `CDATA XML` tags would cause the app to crash
[#6982](https://github.com/postmanlabs/postman-app-support/issues/6982)

* Fixed a bug when working with languages written from right to left, where selecting a portion of the text would return text from the opposite side
[#6493](https://github.com/postmanlabs/postman-app-support/issues/6493)

* Fixed a bug when beautifying JSON in the request body, where it wouldn't work if there were Postman variables
[#4313](https://github.com/postmanlabs/postman-app-support/issues/4313)

* Fixed a bug when using non-monospace fonts in the text editors where the cursor position was calculated incorrectly
[#2985](https://github.com/postmanlabs/postman-app-support/issues/2985)

* Fixed a bug where checking for updates multiple times would result in an error.
* Fixed a bug when adding a value to an empty environment variable where the new value wouldn't save.
* Fixed an issue when loading a request in a tab that caused the contents to flicker.
* Fixed an issue that caused the unsaved changes icon to flicker when the cursor was nearby.


text:
<?php

class Member extends BaseController
{
    public function __construct()
    {
        parent::__construct();
        $this->load->helper("url");
        $this->load->model("MemberModel");
        $this->load->model('OrderModel');
    }

    public function memberlist()
    {
        $member = $this->MemberModel->getMemberList();
        $data["member"] = $member;
        $this->load->view('member_list', $data);
    }

    public function add()
    {
        $this->loadView('add_member');
    }

    public function resetPassword()
    {
        $member_id = $this->input->post('member_id');
        $result = $this->MemberModel->updateMemberPassword($member_id);
        return $this->rspsJSON(true, '', $result);
    }

    public function addMember()
    {
        $username = $this->input->post('username');
        $name = $this->input->post('name');
        $password = $this->input->post('password');
        $phone = $this->input->post('phone');
        $email = $this->input->post('email');
        $sex = $this->input->post('sex');
        $birthday = $this->input->post('birthday');
        $signup_time = date('y-m-d h:i:s', time());
        //查询会员名是否已经存在
        if ($this->MemberModel->SelectMemberInformation($username)) {
            $this->rspsJSON(false, '该会员名已存在', '');
        } else {
            //插入会员信息到tbl_member表中
            $encryptedPassword = sha1($password);
            $data = $this->MemberModel->insertMemberInformation($username, $name, $encryptedPassword, $phone, $email, $sex, $birthday, $signup_time);
            $this->rspsJSON(true, '', $data);
        }

    }

    /*
        public function deleteMember()
        {
            $memberId = $this->input->post('memberId');
            $result = $this->MemberModel->deleteMemberById($memberId);
            $this->rspsJSON(true, '', $result);
        }*/

    public function feedback($username = "", $feedback_status = 0, $feedback_type = 0)
    {
        date_default_timezone_set('PRC');
        $search_feedback = array(
            'username' => $username ? $username : urldecode($username),
            'feedback_status' => $feedback_status,
            'feedback_type' => $feedback_type
        );
        $feedback = $this->MemberModel->getMemberFeedback($search_feedback);
        foreach ($feedback as $item) {
            switch ($item->msg_type) {
                case 1:
                    $item->msg_type = '投诉';
                    break;
                case 2:
                    $item->msg_type = '售后';
                    break;
                case 3:
                    $item->msg_type = '求购';
                    break;
                case 4:
                    $item->msg_type = '询问';
                    break;
                default:
                    $item->msg_type = '留言';
            }
            switch ($item->msg_status) {
                case 1:
                    $item->msg_status = '未回复';
                    break;
                case 2:
                    $item->msg_status = '已回复';
                    break;
            }
        }
        $data["feedback"] = $feedback;
        $this->load->view('feedback_list', $data);
    }

    /*
        public function edit($memberId)
        {
            $member = $this->MemberModel->getMemberInformation($memberId);
            $member["birthdayYear"] = substr($member["birthday"], 0, 4);
            $member["birthdayMonth"] = substr($member["birthday"], 5, 2);
            $member["birthdayDay"] = substr($member["birthday"], 8, 2);
            $data["member"] = $member;
            $this->loadView('edit_member', $data);
        }*/

    public function deleteFeedback()
    {
        $msg_id = $this->input->post('msgId');
        $data = $this->MemberModel->deleteMemberFeedback($msg_id);
        $this->rspsJSON(true, '', $data);
    }

    public function editMember()
    {
        $memberId = $this->input->post('memberId');
        $username = $this->input->post('username');
        $name = $this->input->post('name');
        $password = $this->input->post('password');
        $phone = $this->input->post('phone');
        $email = $this->input->post('email');
        $sex = $this->input->post('sex');
        $birthday = $this->input->post('birthday');
        //检验该会员所输入的密码是否正确
        $encryptedPassword = sha1($password);
        if ($this->MemberModel->verifyMemberPassword($memberId, $encryptedPassword)) {
            $data = $this->MemberModel->modifyMemberInformation($memberId, $username, $name, $phone, $email, $sex, $birthday);
            $this->rspsJSON(true, '', $data);
        } else {
            $this->rspsJSON(false, '密码错误', '');
        }
    }

    public function reply($msg_id)
    {
        $feedback = $this->MemberModel->getFeedbackInformation($msg_id);
        $data["feedback"] = $feedback;
        $this->loadView('reply_feedback', $data);

    }

    public function replyFeedback()
    {
        $msg_id = $this->input->post('msg_id');
        $reply_content = $this->input->post('reply_content');
        $result = $this->MemberModel->addReplyFeedback($msg_id, $reply_content);
        $this->rspsJSON(true, '', $result);
    }

    public function detail($user_id)
    {
        $address = $this->MemberModel->getUserAddress($user_id);
        foreach ($address as $item) {
            $country = $this->OrderModel->getRegionName($item->country);
            $province = $this->OrderModel->getRegionName($item->province);
            $city = $this->OrderModel->getRegionName($item->city);
            $district = $this->OrderModel->getRegionName($item->district);
            $item->country = $country["region_name"];
            $item->province = $province["region_name"];
            $item->city = $city["region_name"];
            $item->district = $district["region_name"];
        }
        $order = $this->OrderModel->getUserOrderByUserId($user_id);
        $data["address"] = $address;
        $data["order"] = $order;
        $this->load->view('member_detail', $data);
    }
}


text:
.wp-editor-expand #wp-content-editor-tools{
    border-bottom: 0;
}
#hpb-button.button-primary span.wp-media-buttons-icon:before{
    color: #fff;
}
#page-builder{
    display: none;
}
.text-center{
    text-align: center;
}
#add-new-hpb-widget{
    padding: 10px;
    margin: auto;
    width: 90%;
    height: auto;
    font-size: 18px;
    line-height: 18px;
}
#sortable{
    min-height: 50px;
}
.avaliable-home-widgets .widget-title-action{
    display: none;
}
.widget-action{
    display: block;
    height: 20px;
}
#sortable .widget.open .widget-inside
{
    display: block;
    padding: 15px;
}
.avaliable-home-widgets .widget{
    width: auto;
    display: inline-block;
    z-index: 1000;
}
.col-3{
  width: 24%;
  display: inline-block;
}
.col-4{
  width: 32%;
  display: inline-block;
}
.col-8{
  width: 67%;
  display: inline-block;
}
.col-9{
  width: 75%;
  display: inline-block;
}
.spinner-contianer{
  width: 20px;
  margin: auto;
  padding-bottom: 35px;
}


text:
package com.smartdevicelink.exception;

public class SdlException extends Exception {

	private static final long serialVersionUID = 5922492291870772815L;

	protected Throwable detail = null;
	private SdlExceptionCause _sdlExceptionCause = null;

	public SdlException(String msg, SdlExceptionCause exceptionCause) {
		super(msg);
		_sdlExceptionCause = exceptionCause;
	}

	public SdlException(String msg, Throwable ex, SdlExceptionCause exceptionCause) {
		super(msg + " --- Check inner exception for diagnostic details");
		detail = ex;
		_sdlExceptionCause = exceptionCause;
	}

	public SdlException(Throwable ex) {
		super(ex.getMessage());
		detail = ex;
	}

	public SdlExceptionCause getSdlExceptionCause() {
		return _sdlExceptionCause;
	}

	public Throwable getInnerException() {
		return detail;
	}

	public String toString() {
		String ret = this.getClass().getName();
		ret += ": " + this.getMessage();
		if(this.getSdlExceptionCause() != null){
			ret += "\nSdlExceptionCause: " + this.getSdlExceptionCause().name();
		}
		if (detail != null) {
			ret += "\nnested: " + detail.toString();
			detail.printStackTrace();
		}
		return ret;
	}
}


text:
class MarkdownController < ApplicationController
  def preview
    render layout: false
  end
end


text:
MongoDB, NodeJS, Multi-tenancy Startup Template

It's super easy, to setup multi-tenancy application.

Sepalate Client and Server apps, REST API, Token base Authorization !

          Try now!

It's all included!

 Subdomain for each client

 Separate MongoDB per Client

 Centralized Identity Management Database

 Token base Authentication

 Separate Client and Server Apps

 Components and Module based Architecture

 REST API

 A lot more...


text:
from .core import EventState  # noqa: F401
from .core import OperatableStateMachine, ConcurrencyContainer, PriorityContainer  # noqa: F401

from .behavior import Behavior  # noqa: F401

from .behavior_library import BehaviorLibrary  # noqa: F401

from .logger import Logger  # noqa: F401
from .state_logger import StateLogger  # noqa: F401

class Autonomy:
    """
    Provides constants for the available required Autonomy Levels.
    """

    Inherit = 0
    """
    Use this whenever you want to rely on an already defined level of autonomy
    Typical situations: Outcomes of a contained state machine or behavior, outcome of the input request state
    """

    Off = 0
    """
    Use this when no level of autonomy is required, the Autonomy Level needs to be at least 'Off'.
    Typical situations: Outcomes that report internal software errors or thrown exceptions.
    """

    Low = 1
    """
    Use this for reliable decisions that only need validation in the 'low' autonomy mode.
    """

    High = 2
    """
    Use this for more important or high level decisions that will only be executed autonomously
    when in full autonomy and need validation in the 'high' autonomy mode.
    """

    Full = 3
    """
    Use this for outcomes that always need an operator input.
    A use of this level is not recommended.
    """


text:
* WordPress Bedrock setup
* Theme based on Bladerunner
* Content with Papi modules

Development runs on Docker with bedrock-docker and deployments done with PHP Deployer.


text:
title: Webinar: 2GM TOWN HALL MEETING: 2021 Q1
date:  February 5, 2021
description: 2GM Town Hall Meetings provide the Groovy, Grails, and Micronaut communities a place to gather once per quarter to review the most up-to-date news and resources available, celebrate accomplishments, ask questions, and participate more fully in the 2GM ecosystems.
author: Jen Wiese
image: grails-blog-index-4.png
video: https://www.youtube.com/watch?v=j7sf8G63OrI
slides: https://objectcomputing.com/download_file/5088
---

# [%title]

[%author]

[%date]

Tags: #webinar #townhall

A big thanks to everyone who joined us for our first 2GM Town Hall of 2021!  We had a great time and learned about several exciting goings on within the Groovy, Grails, and Micronaut communities. For those of you who missed the live event, the recording is embedded below.

I would like to take this opportunity to thank our awesome panel of experts:

James Kleeh, Micronaut Development Lead
Puneet Behl, Grails Development Lead
Paul King, Groovy Development Lead
Plus, our guest panelist, Graeme Rocher, Architect at Oracle

Stay tuned for details about our next 2GM Town Hall meeting.


text:
RSpec.describe Hyrax::Works::ManagedWorksService, clean_repo: true do
  let(:current_ability) { instance_double(Ability, admin?: true) }
  let(:scope) { FakeSearchBuilderScope.new(current_ability: current_ability) }

  describe '.managed_works_count' do
    let!(:work) { FactoryBot.create(:public_work) }

    it 'returns number of works that can be managed' do
      expect(described_class.managed_works_count(scope: scope)).to eq(1)
    end
  end
end


text:
"""Information registry to register operator information for compiler"""
import tvm

class OpPattern(object):
    """Operator generic patterns

    See Also
    --------
    top.tag : Contains explanation of the tag type.
    """
    # Elementwise operator
    ELEMWISE = 0
    # Broadcast operator
    BROADCAST = 1
    # Injective mapping
    INJECTIVE = 2
    # Comunication
    COMM_REDUCE = 3
    # Complex op, can still fuse ewise into it
    OUT_ELEMWISE_FUSABLE = 4
    # Not fusable opaque op
    OPAQUE = 8

_register_compute = tvm.get_global_func("nnvm._register_compute")
_register_schedule = tvm.get_global_func("nnvm._register_schedule")
_register_pattern = tvm.get_global_func("nnvm._register_pattern")
_register_alter_op_layout = tvm.get_global_func("nnvm.compiler._register_alter_op_layout")

def register_compute(op_name, f=None, level=10):
    """Register compute function for operator

    Parameters
    ----------
    op_name : str
        The name of operator

    f : function
        The schedule function

    level : int
        The priority level

    Returns
    -------
    fregister : function
        Register function if f is not specified.
    """
    def register(myf):
        """internal register function"""
        _register_compute(op_name, myf, level)
        return myf
    return register(f) if f else register

def register_schedule(op_name, f=None, level=10):
    """Register schedule function for operator

    Parameters
    ----------
    op_name : str
        The name of operator

    f : function
        The schedule function

    level : int
        The priority level

    Returns
    -------
    fregister : function
        Register function if f is not specified.
    """
    def register(myf):
        """internal register function"""
        _register_schedule(op_name, myf, level)
        return myf
    return register(f) if f else register

def register_pattern(op_name, pattern, level=10):
    """Register pattern code for operator

    Parameters
    ----------
    op_name : str
        The name of operator

    pattern : int
        The pattern code.

    level : int
        The priority level
    """
    _register_pattern(op_name, pattern, level)

def register_alter_op_layout(op_name, f=None, level=10):
    """Register alter layout function for operator

    Parameters
    ----------
    op_name : str
        The name of operator

    f : function
        The schedule function

    level : int
        The priority level

    Returns
    -------
    fregister : function
        Register function if f is not specified.
    """
    def register(myf):
        """internal register function"""
        _register_alter_op_layout(op_name, myf, level)
        return myf
    return register(f) if f else register


text:
<?php
/**
 * PostFixture
 *
 */
class PostFixture extends CakeTestFixture {

/**
 * Fields
 *
 * @var array
 */
	public $fields = array(
		'id' => array('type' => 'biginteger', 'null' => false, 'default' => null, 'key' => 'primary'),
		'created' => array('type' => 'datetime', 'null' => false, 'default' => null),
		'content' => array('type' => 'text', 'null' => false, 'default' => null, 'collate' => 'latin1_swedish_ci', 'charset' => 'latin1'),
		'title' => array('type' => 'text', 'null' => false, 'default' => null, 'collate' => 'latin1_swedish_ci', 'charset' => 'latin1'),
		'published' => array('type' => 'boolean', 'null' => false, 'default' => '1'),
		'commentable' => array('type' => 'boolean', 'null' => false, 'default' => '1'),
		'modified' => array('type' => 'datetime', 'null' => false, 'default' => null),
		'project_id' => array('type' => 'biginteger', 'null' => true, 'default' => null),
		'slug' => array('type' => 'string', 'null' => false, 'default' => null, 'key' => 'unique', 'collate' => 'latin1_swedish_ci', 'charset' => 'latin1'),
		'user_id' => array('type' => 'biginteger', 'null' => false, 'default' => null),
		'indexes' => array(
			'PRIMARY' => array('column' => 'id', 'unique' => 1),
			'id' => array('column' => 'id', 'unique' => 1),
			'slug' => array('column' => 'slug', 'unique' => 1)
		),
		'tableParameters' => array('charset' => 'latin1', 'collate' => 'latin1_swedish_ci', 'engine' => 'InnoDB')
	);

/**
 * Records
 *
 * @var array
 */
	public $records = array(
		array(
			'id' => '',
			'created' => '2014-01-29 12:10:36',
			'content' => 'Lorem ipsum dolor sit amet, aliquet feugiat. Convallis morbi fringilla gravida, phasellus feugiat dapibus velit nunc, pulvinar eget sollicitudin venenatis cum nullam, vivamus ut a sed, mollitia lectus. Nulla vestibulum massa neque ut et, id hendrerit sit, feugiat in taciti enim proin nibh, tempor dignissim, rhoncus duis vestibulum nunc mattis convallis.',
			'title' => 'Lorem ipsum dolor sit amet, aliquet feugiat. Convallis morbi fringilla gravida, phasellus feugiat dapibus velit nunc, pulvinar eget sollicitudin venenatis cum nullam, vivamus ut a sed, mollitia lectus. Nulla vestibulum massa neque ut et, id hendrerit sit, feugiat in taciti enim proin nibh, tempor dignissim, rhoncus duis vestibulum nunc mattis convallis.',
			'published' => 1,
			'commentable' => 1,
			'modified' => '2014-01-29 12:10:36',
			'project_id' => '',
			'slug' => 'Lorem ipsum dolor sit amet',
			'user_id' => ''
		),
	);

}


text:
using System;
using System.Xml.Serialization;

namespace Aop.Api.Domain
{
    /// <summary>
    /// MarketingItemSelection Data Structure.
    /// </summary>
    [Serializable]
    public class MarketingItemSelection : AopObject
    {
        /// <summary>
        /// 营销项目ID
        /// </summary>
        [XmlElement("id")]
        public string Id { get; set; }
    }
}


text:
import sys
import os

import git

from git.test.lib import (
    TestBase,
    with_rw_repo
)
from gitdb.test.lib import with_rw_directory
from git.exc import (
    InvalidGitRepositoryError,
    RepositoryDirtyError
)
from git.objects.submodule.base import Submodule
from git.objects.submodule.root import RootModule, RootUpdateProgress
from git.util import to_native_path_linux, join_path_native
from git.compat import string_types
from git.repo.fun import (
    find_git_dir,
    touch
)

# Change the configuration if possible to prevent the underlying memory manager
# to keep file handles open. On windows we get problems as they are not properly
# closed due to mmap bugs on windows (as it appears)
if sys.platform == 'win32':
    try:
        import smmap.util
        smmap.util.MapRegion._test_read_into_memory = True
    except ImportError:
        sys.stderr.write("The submodule tests will fail as some files cannot be removed due to open file handles.\n")
        sys.stderr.write(
            "The latest version of gitdb uses a memory map manager which can be configured to work around this problem")
# END handle windows platform

class TestRootProgress(RootUpdateProgress):

    """Just prints messages, for now without checking the correctness of the states"""

    def update(self, op, cur_count, max_count, message=''):
        print(op, cur_count, max_count, message)

prog = TestRootProgress()

class TestSubmodule(TestBase):

    k_subm_current = "c15a6e1923a14bc760851913858a3942a4193cdb"
    k_subm_changed = "394ed7006ee5dc8bddfd132b64001d5dfc0ffdd3"
    k_no_subm_tag = "0.1.6"

    def _do_base_tests(self, rwrepo):
        """Perform all tests in the given repository, it may be bare or nonbare"""
        # manual instantiation
        smm = Submodule(rwrepo, "\0" * 20)
        # name needs to be set in advance
        self.failUnlessRaises(AttributeError, getattr, smm, 'name')

        # iterate - 1 submodule
        sms = Submodule.list_items(rwrepo, self.k_subm_current)
        assert len(sms) == 1
        sm = sms[0]

        # at a different time, there is None
        assert len(Submodule.list_items(rwrepo, self.k_no_subm_tag)) == 0

        assert sm.path == 'git/ext/gitdb'
        assert sm.path != sm.name                   # in our case, we have ids there, which don't equal the path
        assert sm.url.endswith('github.com/gitpython-developers/gitdb.git')
        assert sm.branch_path == 'refs/heads/master'            # the default ...
        assert sm.branch_name == 'master'
        assert sm.parent_commit == rwrepo.head.commit
        # size is always 0
        assert sm.size == 0
        # the module is not checked-out yet
        self.failUnlessRaises(InvalidGitRepositoryError, sm.module)

        # which is why we can't get the branch either - it points into the module() repository
        self.failUnlessRaises(InvalidGitRepositoryError, getattr, sm, 'branch')

        # branch_path works, as its just a string
        assert isinstance(sm.branch_path, string_types)

        # some commits earlier we still have a submodule, but its at a different commit
        smold = next(Submodule.iter_items(rwrepo, self.k_subm_changed))
        assert smold.binsha != sm.binsha
        assert smold != sm                  # the name changed

        # force it to reread its information
        del(smold._url)
        smold.url == sm.url

        # test config_reader/writer methods
        sm.config_reader()
        new_smclone_path = None             # keep custom paths for later
        new_csmclone_path = None                #
        if rwrepo.bare:
            self.failUnlessRaises(InvalidGitRepositoryError, sm.config_writer)
        else:
            writer = sm.config_writer()
            # for faster checkout, set the url to the local path
            new_smclone_path = to_native_path_linux(join_path_native(self.rorepo.working_tree_dir, sm.path))
            writer.set_value('url', new_smclone_path)
            writer.release()
            assert sm.config_reader().get_value('url') == new_smclone_path
            assert sm.url == new_smclone_path
        # END handle bare repo
        smold.config_reader()

        # cannot get a writer on historical submodules
        if not rwrepo.bare:
            self.failUnlessRaises(ValueError, smold.config_writer)
        # END handle bare repo

        # make the old into a new - this doesn't work as the name changed
        self.failUnlessRaises(ValueError, smold.set_parent_commit, self.k_subm_current)
        # the sha is properly updated
        smold.set_parent_commit(self.k_subm_changed + "~1")
        assert smold.binsha != sm.binsha

        # raises if the sm didn't exist in new parent - it keeps its
        # parent_commit unchanged
        self.failUnlessRaises(ValueError, smold.set_parent_commit, self.k_no_subm_tag)

        # TEST TODO: if a path in the gitmodules file, but not in the index, it raises

        # TEST UPDATE
        ##############
        # module retrieval is not always possible
        if rwrepo.bare:
            self.failUnlessRaises(InvalidGitRepositoryError, sm.module)
            self.failUnlessRaises(InvalidGitRepositoryError, sm.remove)
            self.failUnlessRaises(InvalidGitRepositoryError, sm.add, rwrepo, 'here', 'there')
        else:
            # its not checked out in our case
            self.failUnlessRaises(InvalidGitRepositoryError, sm.module)
            assert not sm.module_exists()

            # currently there is only one submodule
            assert len(list(rwrepo.iter_submodules())) == 1
            assert sm.binsha != "\0" * 20

            # TEST ADD
            ###########
            # preliminary tests
            # adding existing returns exactly the existing
            sma = Submodule.add(rwrepo, sm.name, sm.path)
            assert sma.path == sm.path

            # no url and no module at path fails
            self.failUnlessRaises(ValueError, Submodule.add, rwrepo, "newsubm", "pathtorepo", url=None)

            # CONTINUE UPDATE
            #################

            # lets update it - its a recursive one too
            newdir = os.path.join(sm.abspath, 'dir')
            os.makedirs(newdir)

            # update fails if the path already exists non-empty
            self.failUnlessRaises(OSError, sm.update)
            os.rmdir(newdir)

            # dry-run does nothing
            sm.update(dry_run=True, progress=prog)
            assert not sm.module_exists()

            assert sm.update() is sm
            sm_repopath = sm.path               # cache for later
            assert sm.module_exists()
            assert isinstance(sm.module(), git.Repo)
            assert sm.module().working_tree_dir == sm.abspath

            # INTERLEAVE ADD TEST
            #####################
            # url must match the one in the existing repository ( if submodule name suggests a new one )
            # or we raise
            self.failUnlessRaises(ValueError, Submodule.add, rwrepo, "newsubm", sm.path, "git://someurl/repo.git")

            # CONTINUE UPDATE
            #################
            # we should have setup a tracking branch, which is also active
            assert sm.module().head.ref.tracking_branch() is not None

            # delete the whole directory and re-initialize
            assert len(sm.children()) != 0
            # shutil.rmtree(sm.abspath)
            sm.remove(force=True, configuration=False)
            assert len(sm.children()) == 0
            # dry-run does nothing
            sm.update(dry_run=True, recursive=False, progress=prog)
            assert len(sm.children()) == 0

            sm.update(recursive=False)
            assert len(list(rwrepo.iter_submodules())) == 2
            assert len(sm.children()) == 1          # its not checked out yet
            csm = sm.children()[0]
            assert not csm.module_exists()
            csm_repopath = csm.path

            # adjust the path of the submodules module to point to the local destination
            new_csmclone_path = to_native_path_linux(join_path_native(self.rorepo.working_tree_dir, sm.path, csm.path))
            writer = csm.config_writer()
            writer.set_value('url', new_csmclone_path)
            writer.release()
            assert csm.url == new_csmclone_path

            # dry-run does nothing
            assert not csm.module_exists()
            sm.update(recursive=True, dry_run=True, progress=prog)
            assert not csm.module_exists()

            # update recursively again
            sm.update(recursive=True)
            assert csm.module_exists()

            # tracking branch once again
            csm.module().head.ref.tracking_branch() is not None

            # this flushed in a sub-submodule
            assert len(list(rwrepo.iter_submodules())) == 2

            # reset both heads to the previous version, verify that to_latest_revision works
            smods = (sm.module(), csm.module())
            for repo in smods:
                repo.head.reset('HEAD~2', working_tree=1)
            # END for each repo to reset

            # dry run does nothing
            self.failUnlessRaises(RepositoryDirtyError, sm.update, recursive=True, dry_run=True, progress=prog)
            sm.update(recursive=True, dry_run=True, progress=prog, force=True)
            for repo in smods:
                assert repo.head.commit != repo.head.ref.tracking_branch().commit
            # END for each repo to check

            self.failUnlessRaises(RepositoryDirtyError, sm.update, recursive=True, to_latest_revision=True)
            sm.update(recursive=True, to_latest_revision=True, force=True)
            for repo in smods:
                assert repo.head.commit == repo.head.ref.tracking_branch().commit
            # END for each repo to check
            del(smods)

            # if the head is detached, it still works ( but warns )
            smref = sm.module().head.ref
            sm.module().head.ref = 'HEAD~1'
            # if there is no tracking branch, we get a warning as well
            csm_tracking_branch = csm.module().head.ref.tracking_branch()
            csm.module().head.ref.set_tracking_branch(None)
            sm.update(recursive=True, to_latest_revision=True)

            # to_latest_revision changes the child submodule's commit, it needs an
            # update now
            csm.set_parent_commit(csm.repo.head.commit)

            # undo the changes
            sm.module().head.ref = smref
            csm.module().head.ref.set_tracking_branch(csm_tracking_branch)

            # REMOVAL OF REPOSITOTRY
            ########################
            # must delete something
            self.failUnlessRaises(ValueError, csm.remove, module=False, configuration=False)

            # module() is supposed to point to gitdb, which has a child-submodule whose URL is still pointing
            # to github. To save time, we will change it to
            csm.set_parent_commit(csm.repo.head.commit)
            cw = csm.config_writer()
            cw.set_value('url', self._small_repo_url())
            cw.release()
            csm.repo.index.commit("adjusted URL to point to local source, instead of the internet")

            # We have modified the configuration, hence the index is dirty, and the
            # deletion will fail
            # NOTE: As we did  a few updates in the meanwhile, the indices were reset
            # Hence we create some changes
            csm.set_parent_commit(csm.repo.head.commit)
            writer = sm.config_writer()
            writer.set_value("somekey", "somevalue")
            writer.release()
            writer = csm.config_writer()
            writer.set_value("okey", "ovalue")
            writer.release()
            self.failUnlessRaises(InvalidGitRepositoryError, sm.remove)
            # if we remove the dirty index, it would work
            sm.module().index.reset()
            # still, we have the file modified
            self.failUnlessRaises(InvalidGitRepositoryError, sm.remove, dry_run=True)
            sm.module().index.reset(working_tree=True)

            # enforce the submodule to be checked out at the right spot as well.
            csm.update()
            assert csm.module_exists()
            assert csm.exists()
            assert os.path.isdir(csm.module().working_tree_dir)

            # this would work
            assert sm.remove(force=True, dry_run=True) is sm
            assert sm.module_exists()
            sm.remove(force=True, dry_run=True)
            assert sm.module_exists()

            # but ... we have untracked files in the child submodule
            fn = join_path_native(csm.module().working_tree_dir, "newfile")
            open(fn, 'w').write("hi")
            self.failUnlessRaises(InvalidGitRepositoryError, sm.remove)

            # forcibly delete the child repository
            prev_count = len(sm.children())
            self.failUnlessRaises(ValueError, csm.remove, force=True)
            # We removed sm, which removed all submodules. Howver, the instance we have
            # still points to the commit prior to that, where it still existed
            csm.set_parent_commit(csm.repo.commit(), check=False)
            assert not csm.exists()
            assert not csm.module_exists()
            assert len(sm.children()) == prev_count
            # now we have a changed index, as configuration was altered.
            # fix this
            sm.module().index.reset(working_tree=True)

            # now delete only the module of the main submodule
            assert sm.module_exists()
            sm.remove(configuration=False, force=True)
            assert sm.exists()
            assert not sm.module_exists()
            assert sm.config_reader().get_value('url')

            # delete the rest
            sm_path = sm.path
            sm.remove()
            assert not sm.exists()
            assert not sm.module_exists()
            self.failUnlessRaises(ValueError, getattr, sm, 'path')

            assert len(rwrepo.submodules) == 0

            # ADD NEW SUBMODULE
            ###################
            # add a simple remote repo - trailing slashes are no problem
            smid = "newsub"
            osmid = "othersub"
            nsm = Submodule.add(rwrepo, smid, sm_repopath, new_smclone_path + "/", None, no_checkout=True)
            assert nsm.name == smid
            assert nsm.module_exists()
            assert nsm.exists()
            # its not checked out
            assert not os.path.isfile(join_path_native(nsm.module().working_tree_dir, Submodule.k_modules_file))
            assert len(rwrepo.submodules) == 1

            # add another submodule, but into the root, not as submodule
            osm = Submodule.add(rwrepo, osmid, csm_repopath, new_csmclone_path, Submodule.k_head_default)
            assert osm != nsm
            assert osm.module_exists()
            assert osm.exists()
            assert os.path.isfile(join_path_native(osm.module().working_tree_dir, 'setup.py'))

            assert len(rwrepo.submodules) == 2

            # commit the changes, just to finalize the operation
            rwrepo.index.commit("my submod commit")
            assert len(rwrepo.submodules) == 2

            # needs update as the head changed, it thinks its in the history
            # of the repo otherwise
            nsm.set_parent_commit(rwrepo.head.commit)
            osm.set_parent_commit(rwrepo.head.commit)

            # MOVE MODULE
            #############
            # invalid input
            self.failUnlessRaises(ValueError, nsm.move, 'doesntmatter', module=False, configuration=False)

            # renaming to the same path does nothing
            assert nsm.move(sm_path) is nsm

            # rename a module
            nmp = join_path_native("new", "module", "dir") + "/"  # new module path
            pmp = nsm.path
            assert nsm.move(nmp) is nsm
            nmp = nmp[:-1]          # cut last /
            nmpl = to_native_path_linux(nmp)
            assert nsm.path == nmpl
            assert rwrepo.submodules[0].path == nmpl

            mpath = 'newsubmodule'
            absmpath = join_path_native(rwrepo.working_tree_dir, mpath)
            open(absmpath, 'w').write('')
            self.failUnlessRaises(ValueError, nsm.move, mpath)
            os.remove(absmpath)

            # now it works, as we just move it back
            nsm.move(pmp)
            assert nsm.path == pmp
            assert rwrepo.submodules[0].path == pmp

            # REMOVE 'EM ALL
            ################
            # if a submodule's repo has no remotes, it can't be added without an explicit url
            osmod = osm.module()

            osm.remove(module=False)
            for remote in osmod.remotes:
                remote.remove(osmod, remote.name)
            assert not osm.exists()
            self.failUnlessRaises(ValueError, Submodule.add, rwrepo, osmid, csm_repopath, url=None)
        # END handle bare mode

        # Error if there is no submodule file here
        self.failUnlessRaises(IOError, Submodule._config_parser, rwrepo, rwrepo.commit(self.k_no_subm_tag), True)

    @with_rw_repo(k_subm_current)
    def test_base_rw(self, rwrepo):
        self._do_base_tests(rwrepo)

    @with_rw_repo(k_subm_current, bare=True)
    def test_base_bare(self, rwrepo):
        self._do_base_tests(rwrepo)

    @with_rw_repo(k_subm_current, bare=False)
    def test_root_module(self, rwrepo):
        # Can query everything without problems
        rm = RootModule(self.rorepo)
        assert rm.module() is self.rorepo

        # try attributes
        rm.binsha
        rm.mode
        rm.path
        assert rm.name == rm.k_root_name
        assert rm.parent_commit == self.rorepo.head.commit
        rm.url
        rm.branch

        assert len(rm.list_items(rm.module())) == 1
        rm.config_reader()
        w = rm.config_writer()
        w.release()

        # deep traversal gitdb / async
        rsmsp = [sm.path for sm in rm.traverse()]
        assert len(rsmsp) >= 2          # gitdb and async [and smmap], async being a child of gitdb

        # cannot set the parent commit as root module's path didn't exist
        self.failUnlessRaises(ValueError, rm.set_parent_commit, 'HEAD')

        # TEST UPDATE
        #############
        # setup commit which remove existing, add new and modify existing submodules
        rm = RootModule(rwrepo)
        assert len(rm.children()) == 1

        # modify path without modifying the index entry
        # ( which is what the move method would do properly )
        #==================================================
        sm = rm.children()[0]
        pp = "path/prefix"
        fp = join_path_native(pp, sm.path)
        prep = sm.path
        assert not sm.module_exists()               # was never updated after rwrepo's clone

        # assure we clone from a local source
        writer = sm.config_writer()
        writer.set_value('url', to_native_path_linux(join_path_native(self.rorepo.working_tree_dir, sm.path)))
        writer.release()

        # dry-run does nothing
        sm.update(recursive=False, dry_run=True, progress=prog)
        assert not sm.module_exists()

        sm.update(recursive=False)
        assert sm.module_exists()
        writer = sm.config_writer()
        writer.set_value('path', fp)    # change path to something with prefix AFTER url change
        writer.release()

        # update fails as list_items in such a situations cannot work, as it cannot
        # find the entry at the changed path
        self.failUnlessRaises(InvalidGitRepositoryError, rm.update, recursive=False)

        # move it properly - doesn't work as it its path currently points to an indexentry
        # which doesn't exist ( move it to some path, it doesn't matter here )
        self.failUnlessRaises(InvalidGitRepositoryError, sm.move, pp)
        # reset the path(cache) to where it was, now it works
        sm.path = prep
        sm.move(fp, module=False)       # leave it at the old location

        assert not sm.module_exists()
        cpathchange = rwrepo.index.commit("changed sm path")  # finally we can commit

        # update puts the module into place
        rm.update(recursive=False, progress=prog)
        sm.set_parent_commit(cpathchange)
        assert sm.module_exists()

        # add submodule
        #================
        nsmn = "newsubmodule"
        nsmp = "submrepo"
        subrepo_url = to_native_path_linux(join_path_native(self.rorepo.working_tree_dir, rsmsp[0], rsmsp[1]))
        nsm = Submodule.add(rwrepo, nsmn, nsmp, url=subrepo_url)
        csmadded = rwrepo.index.commit("Added submodule").hexsha    # make sure we don't keep the repo reference
        nsm.set_parent_commit(csmadded)
        assert nsm.module_exists()
        # in our case, the module should not exist, which happens if we update a parent
        # repo and a new submodule comes into life
        nsm.remove(configuration=False, module=True)
        assert not nsm.module_exists() and nsm.exists()

        # dry-run does nothing
        rm.update(recursive=False, dry_run=True, progress=prog)

        # otherwise it will work
        rm.update(recursive=False, progress=prog)
        assert nsm.module_exists()

        # remove submodule - the previous one
        #====================================
        sm.set_parent_commit(csmadded)
        smp = sm.abspath
        assert not sm.remove(module=False).exists()
        assert os.path.isdir(smp)           # module still exists
        csmremoved = rwrepo.index.commit("Removed submodule")

        # an update will remove the module
        # not in dry_run
        rm.update(recursive=False, dry_run=True, force_remove=True)
        assert os.path.isdir(smp)

        # when removing submodules, we may get new commits as nested submodules are auto-committing changes
        # to allow deletions without force, as the index would be dirty otherwise.
        # QUESTION: Why does this seem to work in test_git_submodule_compatibility() ?
        self.failUnlessRaises(InvalidGitRepositoryError, rm.update, recursive=False, force_remove=False)
        rm.update(recursive=False, force_remove=True)
        assert not os.path.isdir(smp)

        # 'apply work' to the nested submodule and assure this is not removed/altered during updates
        # Need to commit first, otherwise submodule.update wouldn't have a reason to change the head
        touch(os.path.join(nsm.module().working_tree_dir, 'new-file'))
        # We cannot expect is_dirty to even run as we wouldn't reset a head to the same location
        assert nsm.module().head.commit.hexsha == nsm.hexsha
        nsm.module().index.add([nsm])
        nsm.module().index.commit("added new file")
        rm.update(recursive=False, dry_run=True, progress=prog)  # would not change head, and thus doens't fail
        # Everything we can do from now on will trigger the 'future' check, so no is_dirty() check will even run
        # This would only run if our local branch is in the past and we have uncommitted changes

        prev_commit = nsm.module().head.commit
        rm.update(recursive=False, dry_run=False, progress=prog)
        assert prev_commit == nsm.module().head.commit, "head shouldn't change, as it is in future of remote branch"

        # this kills the new file
        rm.update(recursive=True, progress=prog, force_reset=True)
        assert prev_commit != nsm.module().head.commit, "head changed, as the remote url and its commit changed"

        # change url ...
        #===============
        # ... to the first repository, this way we have a fast checkout, and a completely different
        # repository at the different url
        nsm.set_parent_commit(csmremoved)
        nsmurl = to_native_path_linux(join_path_native(self.rorepo.working_tree_dir, rsmsp[0]))
        writer = nsm.config_writer()
        writer.set_value('url', nsmurl)
        writer.release()
        csmpathchange = rwrepo.index.commit("changed url")
        nsm.set_parent_commit(csmpathchange)

        # Now nsm head is in the future of the tracked remote branch
        prev_commit = nsm.module().head.commit
        # dry-run does nothing
        rm.update(recursive=False, dry_run=True, progress=prog)
        assert nsm.module().remotes.origin.url != nsmurl

        rm.update(recursive=False, progress=prog, force_reset=True)
        assert nsm.module().remotes.origin.url == nsmurl
        assert prev_commit != nsm.module().head.commit, "Should now point to gitdb"
        assert len(rwrepo.submodules) == 1
        assert not rwrepo.submodules[0].children()[0].module_exists(), "nested submodule should not be checked out"

        # add the submodule's changed commit to the index, which is what the
        # user would do
        # beforehand, update our instance's binsha with the new one
        nsm.binsha = nsm.module().head.commit.binsha
        rwrepo.index.add([nsm])

        # change branch
        #=================
        # we only have one branch, so we switch to a virtual one, and back
        # to the current one to trigger the difference
        cur_branch = nsm.branch
        nsmm = nsm.module()
        prev_commit = nsmm.head.commit
        for branch in ("some_virtual_branch", cur_branch.name):
            writer = nsm.config_writer()
            writer.set_value(Submodule.k_head_option, git.Head.to_full_path(branch))
            writer.release()
            csmbranchchange = rwrepo.index.commit("changed branch to %s" % branch)
            nsm.set_parent_commit(csmbranchchange)
        # END for each branch to change

        # Lets remove our tracking branch to simulate some changes
        nsmmh = nsmm.head
        assert nsmmh.ref.tracking_branch() is None                  # never set it up until now
        assert not nsmmh.is_detached

        # dry run does nothing
        rm.update(recursive=False, dry_run=True, progress=prog)
        assert nsmmh.ref.tracking_branch() is None

        # the real thing does
        rm.update(recursive=False, progress=prog)

        assert nsmmh.ref.tracking_branch() is not None
        assert not nsmmh.is_detached

        # recursive update
        # =================
        # finally we recursively update a module, just to run the code at least once
        # remove the module so that it has more work
        assert len(nsm.children()) >= 1  # could include smmap
        assert nsm.exists() and nsm.module_exists() and len(nsm.children()) >= 1
        # assure we pull locally only
        nsmc = nsm.children()[0]
        writer = nsmc.config_writer()
        writer.set_value('url', subrepo_url)
        writer.release()
        rm.update(recursive=True, progress=prog, dry_run=True)      # just to run the code
        rm.update(recursive=True, progress=prog)

        # gitdb: has either 1 or 2 submodules depending on the version
        assert len(nsm.children()) >= 1 and nsmc.module_exists()

    @with_rw_repo(k_no_subm_tag, bare=False)
    def test_first_submodule(self, rwrepo):
        assert len(list(rwrepo.iter_submodules())) == 0

        for sm_name, sm_path in (('first', 'submodules/first'),
                                 ('second', os.path.join(rwrepo.working_tree_dir, 'submodules/second'))):
            sm = rwrepo.create_submodule(sm_name, sm_path, rwrepo.git_dir, no_checkout=True)
            assert sm.exists() and sm.module_exists()
            rwrepo.index.commit("Added submodule " + sm_name)
        # end for each submodule path to add

        self.failUnlessRaises(ValueError, rwrepo.create_submodule, 'fail', os.path.expanduser('~'))
        self.failUnlessRaises(ValueError, rwrepo.create_submodule, 'fail-too',
                              rwrepo.working_tree_dir + os.path.sep)

    @with_rw_directory
    def test_add_empty_repo(self, rwdir):
        empty_repo_dir = os.path.join(rwdir, 'empty-repo')

        parent = git.Repo.init(os.path.join(rwdir, 'parent'))
        git.Repo.init(empty_repo_dir)

        for checkout_mode in range(2):
            name = 'empty' + str(checkout_mode)
            self.failUnlessRaises(ValueError, parent.create_submodule, name, name,
                                  url=empty_repo_dir, no_checkout=checkout_mode and True or False)
        # end for each checkout mode

    @with_rw_directory
    def test_git_submodules(self, rwdir):
        parent = git.Repo.init(os.path.join(rwdir, 'parent'))
        parent.git.submodule('add', self._small_repo_url(), 'module')
        parent.index.commit("added submodule")

        assert len(parent.submodules) == 1
        sm = parent.submodules[0]

        assert sm.exists() and sm.module_exists()

        clone = git.Repo.clone_from(self._small_repo_url(),
                                    os.path.join(parent.working_tree_dir, 'existing-subrepository'))
        sm2 = parent.create_submodule('nongit-file-submodule', clone.working_tree_dir)
        assert len(parent.submodules) == 2

        for _ in range(2):
            for init in (False, True):
                sm.update(init=init)
                sm2.update(init=init)
            # end for each init state
        # end for each iteration

        sm.move(sm.path + '_moved')
        sm2.move(sm2.path + '_moved')

    @with_rw_directory
    def test_git_submodule_compatibility(self, rwdir):
        parent = git.Repo.init(os.path.join(rwdir, 'parent'))
        sm_path = join_path_native('submodules', 'intermediate', 'one')
        sm = parent.create_submodule('mymodules/myname', sm_path, url=self._small_repo_url())
        parent.index.commit("added submodule")

        def assert_exists(sm, value=True):
            assert sm.exists() == value
            assert sm.module_exists() == value
        # end

        # As git is backwards compatible itself, it would still recognize what we do here ... unless we really
        # muss it up. That's the only reason why the test is still here ... .
        assert len(parent.git.submodule().splitlines()) == 1

        module_repo_path = os.path.join(sm.module().working_tree_dir, '.git')
        assert module_repo_path.startswith(os.path.join(parent.working_tree_dir, sm_path))
        if not sm._need_gitfile_submodules(parent.git):
            assert os.path.isdir(module_repo_path)
            assert not sm.module().has_separate_working_tree()
        else:
            assert os.path.isfile(module_repo_path)
            assert sm.module().has_separate_working_tree()
            assert find_git_dir(module_repo_path) is not None, "module pointed to by .git file must be valid"
        # end verify submodule 'style'

        # test move
        new_sm_path = join_path_native('submodules', 'one')
        sm.move(new_sm_path)
        assert_exists(sm)

        # Add additional submodule level
        csm = sm.module().create_submodule('nested-submodule', join_path_native('nested-submodule', 'working-tree'),
                                           url=self._small_repo_url())
        sm.module().index.commit("added nested submodule")
        sm_head_commit = sm.module().commit()
        assert_exists(csm)

        # Fails because there are new commits, compared to the remote we cloned from
        self.failUnlessRaises(InvalidGitRepositoryError, sm.remove, dry_run=True)
        assert_exists(sm)
        assert sm.module().commit() == sm_head_commit
        assert_exists(csm)

        # rename nested submodule
        # This name would move itself one level deeper - needs special handling internally
        new_name = csm.name + '/mine'
        assert csm.rename(new_name).name == new_name
        assert_exists(csm)
        assert csm.repo.is_dirty(index=True, working_tree=False), "index must contain changed .gitmodules file"
        csm.repo.index.commit("renamed module")

        # keep_going evaluation
        rsm = parent.submodule_update()
        assert_exists(sm)
        assert_exists(csm)
        csm_writer = csm.config_writer().set_value('url', 'bar')
        csm_writer.release()
        csm.repo.index.commit("Have to commit submodule change for algorithm to pick it up")
        assert csm.url == 'bar'

        self.failUnlessRaises(Exception, rsm.update, recursive=True, to_latest_revision=True, progress=prog)
        assert_exists(csm)
        rsm.update(recursive=True, to_latest_revision=True, progress=prog, keep_going=True)

        # remove
        sm_module_path = sm.module().git_dir

        for dry_run in (True, False):
            sm.remove(dry_run=dry_run, force=True)
            assert_exists(sm, value=dry_run)
            assert os.path.isdir(sm_module_path) == dry_run
        # end for each dry-run mode

    @with_rw_directory
    def test_rename(self, rwdir):
        parent = git.Repo.init(os.path.join(rwdir, 'parent'))
        sm_name = 'mymodules/myname'
        sm = parent.create_submodule(sm_name, sm_name, url=self._small_repo_url())
        parent.index.commit("Added submodule")

        assert sm.rename(sm_name) is sm and sm.name == sm_name
        assert not sm.repo.is_dirty(index=True, working_tree=False, untracked_files=False)

        new_path = 'renamed/myname'
        assert sm.move(new_path).name == new_path

        new_sm_name = "shortname"
        assert sm.rename(new_sm_name) is sm
        assert sm.repo.is_dirty(index=True, working_tree=False, untracked_files=False)
        assert sm.exists()

        sm_mod = sm.module()
        if os.path.isfile(os.path.join(sm_mod.working_tree_dir, '.git')) == sm._need_gitfile_submodules(parent.git):
            assert sm_mod.git_dir.endswith(join_path_native('.git', 'modules', new_sm_name))
        # end

    @with_rw_directory
    def test_branch_renames(self, rw_dir):
        # Setup initial sandbox:
        # parent repo has one submodule, which has all the latest changes
        source_url = self._small_repo_url()
        sm_source_repo = git.Repo.clone_from(source_url, os.path.join(rw_dir, 'sm-source'), b='master')
        parent_repo = git.Repo.init(os.path.join(rw_dir, 'parent'))
        sm = parent_repo.create_submodule('mysubmodule', 'subdir/submodule',
                                          sm_source_repo.working_tree_dir, branch='master')
        parent_repo.index.commit('added submodule')
        assert sm.exists()

        # Create feature branch with one new commit in submodule source
        sm_fb = sm_source_repo.create_head('feature')
        sm_fb.checkout()
        new_file = touch(os.path.join(sm_source_repo.working_tree_dir, 'new-file'))
        sm_source_repo.index.add([new_file])
        sm.repo.index.commit("added new file")

        # change designated submodule checkout branch to the new upstream feature branch
        smcw = sm.config_writer()
        smcw.set_value('branch', sm_fb.name)
        smcw.release()
        assert sm.repo.is_dirty(index=True, working_tree=False)
        sm.repo.index.commit("changed submodule branch to '%s'" % sm_fb)

        # verify submodule update with feature branch that leaves currently checked out branch in it's past
        sm_mod = sm.module()
        prev_commit = sm_mod.commit()
        assert sm_mod.head.ref.name == 'master'
        assert parent_repo.submodule_update()
        assert sm_mod.head.ref.name == sm_fb.name
        assert sm_mod.commit() == prev_commit, "Without to_latest_revision, we don't change the commit"

        assert parent_repo.submodule_update(to_latest_revision=True)
        assert sm_mod.head.ref.name == sm_fb.name
        assert sm_mod.commit() == sm_fb.commit

        # Create new branch which is in our past, and thus seemingly unrelated to the currently checked out one
        # To make it even 'harder', we shall fork and create a new commit
        sm_pfb = sm_source_repo.create_head('past-feature', commit='HEAD~20')
        sm_pfb.checkout()
        sm_source_repo.index.add([touch(os.path.join(sm_source_repo.working_tree_dir, 'new-file'))])
        sm_source_repo.index.commit("new file added, to past of '%r'" % sm_fb)

        # Change designated submodule checkout branch to a new commit in its own past
        smcw = sm.config_writer()
        smcw.set_value('branch', sm_pfb.path)
        smcw.release()
        sm.repo.index.commit("changed submodule branch to '%s'" % sm_pfb)

        # Test submodule updates - must fail if submodule is dirty
        touch(os.path.join(sm_mod.working_tree_dir, 'unstaged file'))
        # This doesn't fail as our own submodule binsha didn't change, and the reset is only triggered if
        # to latest revision is True.
        parent_repo.submodule_update(to_latest_revision=False)
        sm_mod.head.ref.name == sm_pfb.name, "should have been switched to past head"
        sm_mod.commit() == sm_fb.commit, "Head wasn't reset"

        self.failUnlessRaises(RepositoryDirtyError, parent_repo.submodule_update, to_latest_revision=True)
        parent_repo.submodule_update(to_latest_revision=True, force_reset=True)
        assert sm_mod.commit() == sm_pfb.commit, "Now head should have been reset"
        assert sm_mod.head.ref.name == sm_pfb.name


text:
import NonIndexedFasta from "./nonIndexedFasta.js"
import FastaSequence from "./indexedFasta.js"
import {isDataURL} from "../util/igvUtils.js"
import ChromSizes from "./chromSizes.js"

async function loadFasta(reference) {

    let fasta
    if ("chromsizes" === reference.format) {
        fasta = new ChromSizes(reference.fastaURL)
    } else if (isDataURL(reference.fastaURL) || reference.indexed === false) {
        fasta = new NonIndexedFasta(reference)
    } else {
        fasta = new FastaSequence(reference)
    }
    await fasta.init()
    return fasta
}

export {loadFasta}


text:
package io.cattle.platform.lifecycle.impl;

import io.cattle.platform.core.constants.InstanceConstants;
import io.cattle.platform.core.constants.NetworkConstants;
import io.cattle.platform.core.model.Instance;
import io.cattle.platform.core.model.Network;
import io.cattle.platform.core.model.Stack;
import io.cattle.platform.core.util.ServiceUtil;
import io.cattle.platform.core.util.SystemLabels;
import io.cattle.platform.lifecycle.NetworkLifecycleManager;
import io.cattle.platform.lifecycle.util.LifecycleException;
import io.cattle.platform.network.IPAssignment;
import io.cattle.platform.network.NetworkService;
import io.cattle.platform.object.ObjectManager;
import io.cattle.platform.object.util.DataAccessor;
import io.cattle.platform.resource.pool.PooledResource;
import io.cattle.platform.resource.pool.PooledResourceOptions;
import io.cattle.platform.resource.pool.ResourcePoolManager;
import io.cattle.platform.resource.pool.util.ResourcePoolConstants;
import org.apache.commons.lang3.StringUtils;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

import static io.cattle.platform.object.util.DataAccessor.*;

public class NetworkLifecycleManagerImpl implements NetworkLifecycleManager {

    ObjectManager objectManager;
    NetworkService networkService;
    ResourcePoolManager poolManager;

    public NetworkLifecycleManagerImpl(ObjectManager objectManager, NetworkService networkService, ResourcePoolManager poolManager) {
        super();
        this.objectManager = objectManager;
        this.networkService = networkService;
        this.poolManager = poolManager;
    }

    @Override
    public void create(Instance instance, Stack stack) throws LifecycleException {
        setupRequestedIp(instance);
        Network network = resolveNetworkMode(instance);
        setDns(instance, stack, network);
    }

    @Override
    public void preRemove(Instance instance) {
        Network network = objectManager.loadResource(Network.class,
                fieldLong(instance, InstanceConstants.FIELD_PRIMARY_NETWORK_ID));

        releaseMacAddress(instance, network);
        releaseIpAddress(instance, network);
    }

    @Override
    public void assignNetworkResources(Instance instance) throws LifecycleException {
        Long networkId = fieldLong(instance, InstanceConstants.FIELD_PRIMARY_NETWORK_ID);
        Network network = objectManager.loadResource(Network.class, networkId);
        if (network == null) {
            return;
        }

        assignIpAddress(instance, network);
        assignMacAddress(instance, network);
        setupCNILabels(instance, network);
    }

    private void setupRequestedIp(Instance instance) {
        String ip = getLabel(instance, SystemLabels.LABEL_REQUESTED_IP);
        if (StringUtils.isNotBlank(ip)) {
            setField(instance, InstanceConstants.FIELD_REQUESTED_IP_ADDRESS, ip);
        }
    }

    private Network resolveNetworkMode(Instance instance) throws LifecycleException {
        String mode = networkService.getNetworkMode(DataAccessor.getFields(instance));
        setField(instance, InstanceConstants.FIELD_NETWORK_MODE, mode);

        Network network = networkService.resolveNetwork(instance.getAccountId(), mode);
        if (network == null && StringUtils.isNotBlank(mode) && !instance.getNativeContainer()) {
            throw new LifecycleException(String.format("Failed to find network for networkMode %s", mode));
        }

        if (network != null) {
            instance.setNetworkId(network.getId());
            setField(instance, InstanceConstants.FIELD_NETWORK_IDS, Arrays.asList(network.getId()));
            setField(instance, InstanceConstants.FIELD_PRIMARY_NETWORK_ID, network.getId());
        }

        return network;
    }

    protected void setDns(Instance instance, Stack stack, Network network) {
        boolean addDns = DataAccessor.fromMap(DataAccessor.fieldMapRO(instance, InstanceConstants.FIELD_LABELS))
                .withKey(SystemLabels.LABEL_USE_RANCHER_DNS)
                .withDefault(true)
                .as(Boolean.class);
        if (!addDns) {
            return;
        }

        for (String dns : DataAccessor.fieldStringList(network, NetworkConstants.FIELD_DNS)) {
            List<String> dnsList = appendToFieldStringList(instance, InstanceConstants.FIELD_DNS, dns);
            setField(instance, InstanceConstants.FIELD_DNS, dnsList);
        }

        List<String> dnsSearchList = appendToFieldStringList(instance, InstanceConstants.FIELD_DNS_SEARCH, ServiceUtil.getContainerNamespace(instance));
        setField(instance, InstanceConstants.FIELD_DNS_SEARCH, dnsSearchList);
        String searchLabel = dnsSearchList.stream().collect(Collectors.joining(","));
        setLabel(instance, SystemLabels.LABEL_DNS_SEARCH, searchLabel);
    }

    private void setupCNILabels(Instance instance, Network network) {
        if (NetworkConstants.KIND_CNI.equals(network.getKind())) {
            String wait = getLabel(instance, SystemLabels.LABEL_CNI_WAIT);
            String netName = getLabel(instance, SystemLabels.LABEL_CNI_NETWORK);
            if (StringUtils.isBlank(wait) || StringUtils.isBlank(netName)) {
                setLabel(instance, SystemLabels.LABEL_CNI_WAIT, "true");
                setLabel(instance, SystemLabels.LABEL_CNI_NETWORK, network.getName());
            }
        }
    }

    private void releaseMacAddress(Instance instance, Network network) {
        poolManager.releaseResource(network, instance, new PooledResourceOptions().withQualifier(ResourcePoolConstants.MAC));
    }

    private void assignMacAddress(Instance instance, Network network) throws LifecycleException {
        String mac = fieldString(instance, InstanceConstants.FIELD_PRIMARY_MAC_ADDRESSS);
        if (StringUtils.isNotBlank(mac)) {
            return;
        }

        PooledResource resource = poolManager.allocateOneResource(network, instance, new PooledResourceOptions().withQualifier(ResourcePoolConstants.MAC));
        if (resource == null) {
            throw new LifecycleException("Failed to allocate MAC from network");
        }

        setField(instance, InstanceConstants.FIELD_PRIMARY_MAC_ADDRESSS, resource.getName());
        setLabel(instance, SystemLabels.LABEL_MAC_ADDRESS, resource.getName());
    }

    private void releaseIpAddress(Instance instance, Network network) {
        networkService.releaseIpAddress(network, instance);
    }

    private void assignIpAddress(Instance instance, Network network) throws LifecycleException {
        String ipAddress = fieldString(instance, InstanceConstants.FIELD_PRIMARY_IP_ADDRESS);
        if (StringUtils.isNotBlank(ipAddress) || !networkService.shouldAssignIpAddress(network)) {
            return;
        }

        IPAssignment assignment = allocateIp(instance, network);
        if (assignment != null) {
            setField(instance, InstanceConstants.FIELD_PRIMARY_IP_ADDRESS, assignment.getIpAddress());
            setField(instance, InstanceConstants.FIELD_MANAGED_IP, "true");
            setLabel(instance, SystemLabels.LABEL_IP_ADDRESS, assignment.getIpAddress());
        }
    }

    private IPAssignment allocateIp(Instance instance, Network network) throws LifecycleException {
        String requestedIp = fieldString(instance, InstanceConstants.FIELD_REQUESTED_IP_ADDRESS);
        IPAssignment ip = networkService.assignIpAddress(network, instance, requestedIp);
        if (ip == null) {
            throw new LifecycleException("Failed to allocate IP from subnet");
        }

        return ip;
    }

}


text:
import Gaffer
import GafferUI

import GafferScene

Gaffer.Metadata.registerNode(

	GafferScene.PrimitiveVariables,

	"description",
	"""
	Adds arbitrary primitive variables to objects. Currently only primitive
	variables with constant interpolation are supported - see the OSLObject
	node for a means of creating variables with vertex interpolation.
	""",

	plugs = {

		"primitiveVariables" : [

			"description",
			"""
			The primitive variables to be applied - arbitrary numbers of user
			defined primitive variables may be added as children of this plug
			via the user interface, or using the CompoundDataPlug API via
			python.
			""",

		]

	}

)


text:
package org.apache.ignite.internal.managers.communication;

import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicBoolean;
import org.apache.ignite.Ignite;
import org.apache.ignite.IgniteException;
import org.apache.ignite.compute.ComputeJob;
import org.apache.ignite.compute.ComputeJobAdapter;
import org.apache.ignite.compute.ComputeJobResult;
import org.apache.ignite.compute.ComputeTaskSplitAdapter;
import org.apache.ignite.internal.util.typedef.G;
import org.apache.ignite.internal.util.typedef.P2;
import org.apache.ignite.resources.IgniteInstanceResource;
import org.apache.ignite.testframework.junits.common.GridCommonAbstractTest;
import org.apache.ignite.testframework.junits.common.GridCommonTest;
import org.junit.Test;

/**
 * Grid communication manager self test.
 */
@GridCommonTest(group = "Kernal Self")
public class GridCommunicationManagerListenersSelfTest extends GridCommonAbstractTest {
    /** */
    public GridCommunicationManagerListenersSelfTest() {
        super(true);
    }

    /**
     * Works fine.
     */
    @Test
    public void testDifferentListeners() {
        Ignite ignite = G.ignite(getTestIgniteInstanceName());

        for (int i = 0; i < 2000; i++) {
            P2<UUID, Object> l = new P2<UUID, Object>() {
                @Override public boolean apply(UUID uuid, Object o) {
                    return false;
                }
            };

            ignite.message().localListen(null, l);
        }

        info(getName() + ": worked without exceptions.");
    }

    /**
     * Fails on the 1001st time.
     */
    @Test
    public void testMultipleExecutionsWithoutListeners() {
        checkLoop(1001);
    }

    /**
     * This is the workaround- as long as we keep a message listener in
     * the stack, our FIFO bug isn't exposed.  Comment above out to see.
     */
    @Test
    public void testOneListener() {
        Ignite ignite = G.ignite(getTestIgniteInstanceName());

        final AtomicBoolean stop = new AtomicBoolean();

        P2<UUID, Object> l = new P2<UUID, Object>() {
            @Override public boolean apply(UUID uuid, Object o) {
                return stop.get();
            }
        };

        try {
            ignite.message().localListen(null, l);

            checkLoop(2000);
        } finally {
            stop.set(true);
        }
    }

    /**
     * Now, our test will fail on the first message added after our safety
     * message listener has been removed.
     */
    @Test
    public void testSingleExecutionWithoutListeners() {
        checkLoop(1);
    }

    /**
     * @param cnt Iteration count.
     */
    private void checkLoop(int cnt) {
        for (int i = 1; i <= cnt; i++) {
            MessageListeningTask t = new MessageListeningTask();

            try {
                G.ignite(getTestIgniteInstanceName()).compute().execute(t.getClass(), null);
            }
            catch (IgniteException e) {
                assert false : "Failed to execute task [iteration=" + i + ", err=" + e.getMessage() + ']';
            }

            if (i % 100 == 0)
                info(getName() + ": through " + i);
        }
    }

    /**
     *
     */
    private static class MessageListeningTask extends ComputeTaskSplitAdapter<Object, Object>
        implements GridMessageListener {
        /** */
        @IgniteInstanceResource
        private transient Ignite ignite;

        /** */
        private AtomicBoolean stop = new AtomicBoolean();

        /** {@inheritDoc} */
        @Override public Collection<? extends ComputeJob> split(int gridSize, Object arg) {
            ignite.message().localListen(null, new P2<UUID, Object>() {
                @Override public boolean apply(UUID uuid, Object o) {
                    return stop.get();
                }
            });

            return Arrays.asList(new ComputeJobAdapter() {
                @Override public Object execute() {
                    return null;
                }
            });
        }

        /** {@inheritDoc} */
        @Override public Object reduce(List<ComputeJobResult> results) {
            stop.set(true);

            return null;
        }

        /** {@inheritDoc} */
        @Override public void onMessage(UUID nodeId, Object msg, byte plc) {
            // No-op.
        }
    }
}


text:
var cache_manager = require('cache-manager');
var s3 = new (require('aws-sdk')).S3({params:{Bucket: process.env.S3_BUCKET_NAME}});

module.exports = {
    init: function() {
        this.cache = cache_manager.caching({
            store: s3_cache, ttl: 10/*seconds*/
        });
    },

    beforePhantomRequest: function(req, res, next) {
        if(req.method !== 'GET') {
            return next();
        }

        this.cache.get(req.prerender.url, function (err, result) {
            if (!err && result) {
                console.log('cache hit');
                res.send(200, result.Body);
            } else {
                next();
            }
        });
    },

    afterPhantomRequest: function(phantom, context, next) {
        this.cache.set(context.request.url, context.response.documentHTML);
        next();
    }
}

var s3_cache = {
    get: function(key, callback) {
        if (process.env.S3_PREFIX_KEY) {
            key = process.env.S3_PREFIX_KEY + '/' + key;
        }

        s3.getObject({
            Key: key
        }, callback);
    },
    set: function(key, value, callback) {
        if (process.env.S3_PREFIX_KEY) {
            key = process.env.S3_PREFIX_KEY + '/' + key;
        }

        var request = s3.putObject({
            Key: key,
            ContentType: 'text/html;charset=UTF-8',
            StorageClass: 'REDUCED_REDUNDANCY',
            Body: value
        }, callback);

        if (!callback) {
            request.send();
        }
    }
}