text:
package graph

import (
	"fmt"
	"io"
	"os"
	"sync"

	"github.com/Sirupsen/logrus"
	"github.com/docker/distribution/registry/client/transport"
	"github.com/docker/docker/image"
	"github.com/docker/docker/pkg/ioutils"
	"github.com/docker/docker/pkg/progressreader"
	"github.com/docker/docker/pkg/streamformatter"
	"github.com/docker/docker/pkg/stringid"
	"github.com/docker/docker/registry"
	"github.com/docker/docker/utils"
)

type v1Pusher struct {
	*TagStore
	endpoint  registry.APIEndpoint
	localRepo Repository
	repoInfo  *registry.RepositoryInfo
	config    *ImagePushConfig
	sf        *streamformatter.StreamFormatter
	session   *registry.Session

	out io.Writer
}

func (p *v1Pusher) Push() (fallback bool, err error) {
	tlsConfig, err := p.registryService.TLSConfig(p.repoInfo.Index.Name)
	if err != nil {
		return false, err
	}
	// Adds Docker-specific headers as well as user-specified headers (metaHeaders)
	tr := transport.NewTransport(
		// TODO(tiborvass): was NoTimeout
		registry.NewTransport(tlsConfig),
		registry.DockerHeaders(p.config.MetaHeaders)...,
	)
	client := registry.HTTPClient(tr)
	v1Endpoint, err := p.endpoint.ToV1Endpoint(p.config.MetaHeaders)
	if err != nil {
		logrus.Debugf("Could not get v1 endpoint: %v", err)
		return true, err
	}
	p.session, err = registry.NewSession(client, p.config.AuthConfig, v1Endpoint)
	if err != nil {
		// TODO(dmcgowan): Check if should fallback
		return true, err
	}
	if err := p.pushRepository(p.config.Tag); err != nil {
		// TODO(dmcgowan): Check if should fallback
		return false, err
	}
	return false, nil
}

// Retrieve the all the images to be uploaded in the correct order
func (p *v1Pusher) getImageList(requestedTag string) ([]string, map[string][]string, error) {
	var (
		imageList   []string
		imagesSeen  = make(map[string]bool)
		tagsByImage = make(map[string][]string)
	)

	for tag, id := range p.localRepo {
		if requestedTag != "" && requestedTag != tag {
			// Include only the requested tag.
			continue
		}

		if utils.DigestReference(tag) {
			// Ignore digest references.
			continue
		}

		var imageListForThisTag []string

		tagsByImage[id] = append(tagsByImage[id], tag)

		for img, err := p.graph.Get(id); img != nil; img, err = p.graph.GetParent(img) {
			if err != nil {
				return nil, nil, err
			}

			if imagesSeen[img.ID] {
				// This image is already on the list, we can ignore it and all its parents
				break
			}

			imagesSeen[img.ID] = true
			imageListForThisTag = append(imageListForThisTag, img.ID)
		}

		// reverse the image list for this tag (so the "most"-parent image is first)
		for i, j := 0, len(imageListForThisTag)-1; i < j; i, j = i+1, j-1 {
			imageListForThisTag[i], imageListForThisTag[j] = imageListForThisTag[j], imageListForThisTag[i]
		}

		// append to main image list
		imageList = append(imageList, imageListForThisTag...)
	}
	if len(imageList) == 0 {
		return nil, nil, fmt.Errorf("No images found for the requested repository / tag")
	}
	logrus.Debugf("Image list: %v", imageList)
	logrus.Debugf("Tags by image: %v", tagsByImage)

	return imageList, tagsByImage, nil
}

// createImageIndex returns an index of an image's layer IDs and tags.
func (s *TagStore) createImageIndex(images []string, tags map[string][]string) []*registry.ImgData {
	var imageIndex []*registry.ImgData
	for _, id := range images {
		if tags, hasTags := tags[id]; hasTags {
			// If an image has tags you must add an entry in the image index
			// for each tag
			for _, tag := range tags {
				imageIndex = append(imageIndex, &registry.ImgData{
					ID:  id,
					Tag: tag,
				})
			}
			continue
		}
		// If the image does not have a tag it still needs to be sent to the
		// registry with an empty tag so that it is associated with the repository
		imageIndex = append(imageIndex, &registry.ImgData{
			ID:  id,
			Tag: "",
		})
	}
	return imageIndex
}

type imagePushData struct {
	id              string
	compatibilityID string
	endpoint        string
}

// lookupImageOnEndpoint checks the specified endpoint to see if an image exists
// and if it is absent then it sends the image id to the channel to be pushed.
func (p *v1Pusher) lookupImageOnEndpoint(wg *sync.WaitGroup, images chan imagePushData, imagesToPush chan string) {
	defer wg.Done()
	for image := range images {
		if err := p.session.LookupRemoteImage(image.compatibilityID, image.endpoint); err != nil {
			logrus.Errorf("Error in LookupRemoteImage: %s", err)
			imagesToPush <- image.id
			continue
		}
		p.out.Write(p.sf.FormatStatus("", "Image %s already pushed, skipping", stringid.TruncateID(image.id)))
	}
}

func (p *v1Pusher) pushImageToEndpoint(endpoint string, imageIDs []string, tags map[string][]string, repo *registry.RepositoryData) error {
	workerCount := len(imageIDs)
	// start a maximum of 5 workers to check if images exist on the specified endpoint.
	if workerCount > 5 {
		workerCount = 5
	}
	var (
		wg           = &sync.WaitGroup{}
		imageData    = make(chan imagePushData, workerCount*2)
		imagesToPush = make(chan string, workerCount*2)
		pushes       = make(chan map[string]struct{}, 1)
	)
	for i := 0; i < workerCount; i++ {
		wg.Add(1)
		go p.lookupImageOnEndpoint(wg, imageData, imagesToPush)
	}
	// start a go routine that consumes the images to push
	go func() {
		shouldPush := make(map[string]struct{})
		for id := range imagesToPush {
			shouldPush[id] = struct{}{}
		}
		pushes <- shouldPush
	}()
	for _, id := range imageIDs {
		compatibilityID, err := p.getV1ID(id)
		if err != nil {
			return err
		}
		imageData <- imagePushData{
			id:              id,
			compatibilityID: compatibilityID,
			endpoint:        endpoint,
		}
	}
	// close the channel to notify the workers that there will be no more images to check.
	close(imageData)
	wg.Wait()
	close(imagesToPush)
	// wait for all the images that require pushes to be collected into a consumable map.
	shouldPush := <-pushes
	// finish by pushing any images and tags to the endpoint.  The order that the images are pushed
	// is very important that is why we are still iterating over the ordered list of imageIDs.
	for _, id := range imageIDs {
		if _, push := shouldPush[id]; push {
			if _, err := p.pushImage(id, endpoint); err != nil {
				// FIXME: Continue on error?
				return err
			}
		}
		for _, tag := range tags[id] {
			p.out.Write(p.sf.FormatStatus("", "Pushing tag for rev [%s] on {%s}", stringid.TruncateID(id), endpoint+"repositories/"+p.repoInfo.RemoteName+"/tags/"+tag))
			compatibilityID, err := p.getV1ID(id)
			if err != nil {
				return err
			}
			if err := p.session.PushRegistryTag(p.repoInfo.RemoteName, compatibilityID, tag, endpoint); err != nil {
				return err
			}
		}
	}
	return nil
}

// pushRepository pushes layers that do not already exist on the registry.
func (p *v1Pusher) pushRepository(tag string) error {
	logrus.Debugf("Local repo: %s", p.localRepo)
	p.out = ioutils.NewWriteFlusher(p.config.OutStream)
	imgList, tags, err := p.getImageList(tag)
	if err != nil {
		return err
	}
	p.out.Write(p.sf.FormatStatus("", "Sending image list"))

	imageIndex := p.createImageIndex(imgList, tags)
	logrus.Debugf("Preparing to push %s with the following images and tags", p.localRepo)
	for _, data := range imageIndex {
		logrus.Debugf("Pushing ID: %s with Tag: %s", data.ID, data.Tag)

		// convert IDs to compatibilityIDs, imageIndex only used in registry calls
		data.ID, err = p.getV1ID(data.ID)
		if err != nil {
			return err
		}
	}

	if _, found := p.poolAdd("push", p.repoInfo.LocalName); found {
		return fmt.Errorf("push or pull %s is already in progress", p.repoInfo.LocalName)
	}
	defer p.poolRemove("push", p.repoInfo.LocalName)

	// Register all the images in a repository with the registry
	// If an image is not in this list it will not be associated with the repository
	repoData, err := p.session.PushImageJSONIndex(p.repoInfo.RemoteName, imageIndex, false, nil)
	if err != nil {
		return err
	}
	nTag := 1
	if tag == "" {
		nTag = len(p.localRepo)
	}
	p.out.Write(p.sf.FormatStatus("", "Pushing repository %s (%d tags)", p.repoInfo.CanonicalName, nTag))
	// push the repository to each of the endpoints only if it does not exist.
	for _, endpoint := range repoData.Endpoints {
		if err := p.pushImageToEndpoint(endpoint, imgList, tags, repoData); err != nil {
			return err
		}
	}
	_, err = p.session.PushImageJSONIndex(p.repoInfo.RemoteName, imageIndex, true, repoData.Endpoints)
	return err
}

func (p *v1Pusher) pushImage(imgID, ep string) (checksum string, err error) {
	jsonRaw, err := p.getV1Config(imgID)
	if err != nil {
		return "", fmt.Errorf("Cannot retrieve the path for {%s}: %s", imgID, err)
	}
	p.out.Write(p.sf.FormatProgress(stringid.TruncateID(imgID), "Pushing", nil))

	compatibilityID, err := p.getV1ID(imgID)
	if err != nil {
		return "", err
	}

	// General rule is to use ID for graph accesses and compatibilityID for
	// calls to session.registry()
	imgData := &registry.ImgData{
		ID: compatibilityID,
	}

	// Send the json
	if err := p.session.PushImageJSONRegistry(imgData, jsonRaw, ep); err != nil {
		if err == registry.ErrAlreadyExists {
			p.out.Write(p.sf.FormatProgress(stringid.TruncateID(imgID), "Image already pushed, skipping", nil))
			return "", nil
		}
		return "", err
	}

	layerData, err := p.graph.TempLayerArchive(imgID, p.sf, p.out)
	if err != nil {
		return "", fmt.Errorf("Failed to generate layer archive: %s", err)
	}
	defer os.RemoveAll(layerData.Name())

	// Send the layer
	logrus.Debugf("rendered layer for %s of [%d] size", imgID, layerData.Size)

	checksum, checksumPayload, err := p.session.PushImageLayerRegistry(imgData.ID,
		progressreader.New(progressreader.Config{
			In:        layerData,
			Out:       p.out,
			Formatter: p.sf,
			Size:      layerData.Size,
			NewLines:  false,
			ID:        stringid.TruncateID(imgID),
			Action:    "Pushing",
		}), ep, jsonRaw)
	if err != nil {
		return "", err
	}
	imgData.Checksum = checksum
	imgData.ChecksumPayload = checksumPayload
	// Send the checksum
	if err := p.session.PushImageChecksumRegistry(imgData, ep); err != nil {
		return "", err
	}

	p.out.Write(p.sf.FormatProgress(stringid.TruncateID(imgID), "Image successfully pushed", nil))
	return imgData.Checksum, nil
}

// getV1ID returns the compatibilityID for the ID in the graph. compatibilityID
// is read from from the v1Compatibility config file in the disk.
func (p *v1Pusher) getV1ID(id string) (string, error) {
	jsonData, err := p.getV1Config(id)
	if err != nil {
		return "", err
	}
	img, err := image.NewImgJSON(jsonData)
	if err != nil {
		return "", err
	}
	return img.ID, nil
}

// getV1Config returns v1Compatibility config for the image in the graph. If
// there is no v1Compatibility file on disk for the image
func (p *v1Pusher) getV1Config(id string) ([]byte, error) {
	jsonData, err := p.graph.GenerateV1CompatibilityChain(id)
	if err != nil {
		return nil, err
	}
	return jsonData, nil
}


text:
@interface UIColor (Photoshop)

+(UIColor *)colorWithHexString:(NSString*)hex;

@end

redpajama_set_name: RedPajamaGithub


text:
Meteor.publish('transactions', function () {
  return Transactions.find({ownerId: this.userId});
});


text: export default (error) => [ error.message, error.stack ].join('\n')


text:
/* global TimelineDataSeries, TimelineGraphView */

'use strict';

const audio2 = document.querySelector('audio#audio2');
const callButton = document.querySelector('button#callButton');
const hangupButton = document.querySelector('button#hangupButton');
const codecSelector = document.querySelector('select#codec');
hangupButton.disabled = true;
callButton.onclick = call;
hangupButton.onclick = hangup;

let pc1;
let pc2;
let localStream;

let bitrateGraph;
let bitrateSeries;

let packetGraph;
let packetSeries;

let lastResult;

const offerOptions = {
  offerToReceiveAudio: 1,
  offerToReceiveVideo: 0,
  voiceActivityDetection: false
};

function gotStream(stream) {
  hangupButton.disabled = false;
  console.log('Received local stream');
  localStream = stream;
  const audioTracks = localStream.getAudioTracks();
  if (audioTracks.length > 0) {
    console.log(`Using Audio device: ${audioTracks[0].label}`);
  }
  localStream.getTracks().forEach(track => pc1.addTrack(track, localStream));
  console.log('Adding Local Stream to peer connection');

  pc1.createOffer(offerOptions)
    .then(gotDescription1, onCreateSessionDescriptionError);

  bitrateSeries = new TimelineDataSeries();
  bitrateGraph = new TimelineGraphView('bitrateGraph', 'bitrateCanvas');
  bitrateGraph.updateEndDate();

  packetSeries = new TimelineDataSeries();
  packetGraph = new TimelineGraphView('packetGraph', 'packetCanvas');
  packetGraph.updateEndDate();
}

function onCreateSessionDescriptionError(error) {
  console.log(`Failed to create session description: ${error.toString()}`);
}

function call() {
  callButton.disabled = true;
  codecSelector.disabled = true;
  console.log('Starting call');
  const servers = null;
  pc1 = new RTCPeerConnection(servers);
  console.log('Created local peer connection object pc1');
  pc1.onicecandidate = e => onIceCandidate(pc1, e);
  pc2 = new RTCPeerConnection(servers);
  console.log('Created remote peer connection object pc2');
  pc2.onicecandidate = e => onIceCandidate(pc2, e);
  pc2.ontrack = gotRemoteStream;
  console.log('Requesting local stream');
  navigator.mediaDevices
    .getUserMedia({
      audio: true,
      video: false
    })
    .then(gotStream)
    .catch(e => {
      alert(`getUserMedia() error: ${e.name}`);
    });
}

function gotDescription1(desc) {
  console.log(`Offer from pc1\n${desc.sdp}`);
  pc1.setLocalDescription(desc)
    .then(() => {
      desc.sdp = forceChosenAudioCodec(desc.sdp);
      pc2.setRemoteDescription(desc).then(() => {
        return pc2.createAnswer().then(gotDescription2, onCreateSessionDescriptionError);
      }, onSetSessionDescriptionError);
    }, onSetSessionDescriptionError);
}

function gotDescription2(desc) {
  console.log(`Answer from pc2\n${desc.sdp}`);
  pc2.setLocalDescription(desc).then(() => {
    desc.sdp = forceChosenAudioCodec(desc.sdp);
    pc1.setRemoteDescription(desc).then(() => {}, onSetSessionDescriptionError);
  }, onSetSessionDescriptionError);
}

function hangup() {
  console.log('Ending call');
  localStream.getTracks().forEach(track => track.stop());
  pc1.close();
  pc2.close();
  pc1 = null;
  pc2 = null;
  hangupButton.disabled = true;
  callButton.disabled = false;
  codecSelector.disabled = false;
}

function gotRemoteStream(e) {
  if (audio2.srcObject !== e.streams[0]) {
    audio2.srcObject = e.streams[0];
    console.log('Received remote stream');
  }
}

function getOtherPc(pc) {
  return (pc === pc1) ? pc2 : pc1;
}

function getName(pc) {
  return (pc === pc1) ? 'pc1' : 'pc2';
}

function onIceCandidate(pc, event) {
  getOtherPc(pc).addIceCandidate(event.candidate)
    .then(
      () => onAddIceCandidateSuccess(pc),
      err => onAddIceCandidateError(pc, err)
    );
  console.log(`${getName(pc)} ICE candidate:\n${event.candidate ? event.candidate.candidate : '(null)'}`);
}

function onAddIceCandidateSuccess() {
  console.log('AddIceCandidate success.');
}

function onAddIceCandidateError(error) {
  console.log(`Failed to add ICE Candidate: ${error.toString()}`);
}

function onSetSessionDescriptionError(error) {
  console.log(`Failed to set session description: ${error.toString()}`);
}

function forceChosenAudioCodec(sdp) {
  return maybePreferCodec(sdp, 'audio', 'send', codecSelector.value);
}

// Copied from AppRTC's sdputils.js:

// Sets |codec| as the default |type| codec if it's present.
// The format of |codec| is 'NAME/RATE', e.g. 'opus/48000'.
function maybePreferCodec(sdp, type, dir, codec) {
  const str = `${type} ${dir} codec`;
  if (codec === '') {
    console.log(`No preference on ${str}.`);
    return sdp;
  }

  console.log(`Prefer ${str}: ${codec}`);

  const sdpLines = sdp.split('\r\n');

  // Search for m line.
  const mLineIndex = findLine(sdpLines, 'm=', type);
  if (mLineIndex === null) {
    return sdp;
  }

  // If the codec is available, set it as the default in m line.
  const codecIndex = findLine(sdpLines, 'a=rtpmap', codec);
  console.log('codecIndex', codecIndex);
  if (codecIndex) {
    const payload = getCodecPayloadType(sdpLines[codecIndex]);
    if (payload) {
      sdpLines[mLineIndex] = setDefaultCodec(sdpLines[mLineIndex], payload);
    }
  }

  sdp = sdpLines.join('\r\n');
  return sdp;
}

// Find the line in sdpLines that starts with |prefix|, and, if specified,
// contains |substr| (case-insensitive search).
function findLine(sdpLines, prefix, substr) {
  return findLineInRange(sdpLines, 0, -1, prefix, substr);
}

// Find the line in sdpLines[startLine...endLine - 1] that starts with |prefix|
// and, if specified, contains |substr| (case-insensitive search).
function findLineInRange(sdpLines, startLine, endLine, prefix, substr) {
  const realEndLine = endLine !== -1 ? endLine : sdpLines.length;
  for (let i = startLine; i < realEndLine; ++i) {
    if (sdpLines[i].indexOf(prefix) === 0) {
      if (!substr ||
        sdpLines[i].toLowerCase().indexOf(substr.toLowerCase()) !== -1) {
        return i;
      }
    }
  }
  return null;
}

// Gets the codec payload type from an a=rtpmap:X line.
function getCodecPayloadType(sdpLine) {
  const pattern = new RegExp('a=rtpmap:(\\d+) \\w+\\/\\d+');
  const result = sdpLine.match(pattern);
  return (result && result.length === 2) ? result[1] : null;
}

// Returns a new m= line with the specified codec as the first one.
function setDefaultCodec(mLine, payload) {
  const elements = mLine.split(' ');

  // Just copy the first three parameters; codec order starts on fourth.
  const newLine = elements.slice(0, 3);

  // Put target payload first and copy in the rest.
  newLine.push(payload);
  for (let i = 3; i < elements.length; i++) {
    if (elements[i] !== payload) {
      newLine.push(elements[i]);
    }
  }
  return newLine.join(' ');
}

// query getStats every second
window.setInterval(() => {
  if (!pc1) {
    return;
  }
  const sender = pc1.getSenders()[0];
  sender.getStats().then(res => {
    res.forEach(report => {
      let bytes;
      let packets;
      if (report.type === 'outbound-rtp') {
        if (report.isRemote) {
          return;
        }
        const now = report.timestamp;
        bytes = report.bytesSent;
        packets = report.packetsSent;
        if (lastResult && lastResult.has(report.id)) {
          // calculate bitrate
          const bitrate = 8 * (bytes - lastResult.get(report.id).bytesSent) /
            (now - lastResult.get(report.id).timestamp);

          // append to chart
          bitrateSeries.addPoint(now, bitrate);
          bitrateGraph.setDataSeries([bitrateSeries]);
          bitrateGraph.updateEndDate();

          // calculate number of packets and append to chart
          packetSeries.addPoint(now, packets -
            lastResult.get(report.id).packetsSent);
          packetGraph.setDataSeries([packetSeries]);
          packetGraph.updateEndDate();
        }
      }
    });
    lastResult = res;
  });
}, 1000);


text:
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE775_Missing_Release_of_File_Descriptor_or_Handle__fopen_no_close_74a.cpp
Label Definition File: CWE775_Missing_Release_of_File_Descriptor_or_Handle__fopen_no_close.label.xml
Template File: source-sinks-74a.tmpl.cpp
*/
/*
 * @description
 * CWE: 775 Missing Release of File Descriptor or Handle After Effective Lifetime
 * BadSource:  Open a file using fopen()
 * Sinks:
 *    GoodSink: Close the file using fclose()
 *    BadSink : Do not close file
 * Flow Variant: 74 Data flow: data passed in a map from one function to another in different source files
 *
 * */

#include "std_testcase.h"
#include <map>

using namespace std;

namespace CWE775_Missing_Release_of_File_Descriptor_or_Handle__fopen_no_close_74
{

#ifndef OMITBAD

/* bad function declaration */
void badSink(map<int, FILE *> dataMap);

void bad()
{
    FILE * data;
    map<int, FILE *> dataMap;
    data = NULL;
    /* POTENTIAL FLAW: Open a file without closing it */
    data = fopen("BadSource_fopen.txt", "w+");
    /* Put data in a map */
    dataMap[0] = data;
    dataMap[1] = data;
    dataMap[2] = data;
    badSink(dataMap);
}

#endif /* OMITBAD */

#ifndef OMITGOOD

/* goodB2G uses the BadSource with the GoodSink */
void goodB2GSink(map<int, FILE *> dataMap);

static void goodB2G()
{
    FILE * data;
    map<int, FILE *> dataMap;
    data = NULL;
    /* POTENTIAL FLAW: Open a file without closing it */
    data = fopen("BadSource_fopen.txt", "w+");
    dataMap[0] = data;
    dataMap[1] = data;
    dataMap[2] = data;
    goodB2GSink(dataMap);
}

void good()
{
    goodB2G();
}

#endif /* OMITGOOD */

} /* close namespace */

/* Below is the main(). It is only used when building this testcase on
   its own for testing or for building a binary to use in testing binary
   analysis tools. It is not used when compiling all the testcases as one
   application, which is how source code analysis tools are tested. */

#ifdef INCLUDEMAIN

using namespace CWE775_Missing_Release_of_File_Descriptor_or_Handle__fopen_no_close_74; /* so that we can use good and bad easily */

int main(int argc, char * argv[])
{
    /* seed randomness */
    srand( (unsigned)time(NULL) );
#ifndef OMITGOOD
    printLine("Calling good()...");
    good();
    printLine("Finished good()");
#endif /* OMITGOOD */
#ifndef OMITBAD
    printLine("Calling bad()...");
    bad();
    printLine("Finished bad()");
#endif /* OMITBAD */
    return 0;
}

#endif


text:
#include "config.h"

#if ENABLE(WEBGL)

#include "OESTextureHalfFloat.h"

namespace WebCore {

OESTextureHalfFloat::OESTextureHalfFloat(WebGLRenderingContextBase* context)
    : WebGLExtension(context)
{
}

OESTextureHalfFloat::~OESTextureHalfFloat()
{
}

WebGLExtension::ExtensionName OESTextureHalfFloat::getName() const
{
    return OESTextureHalfFloatName;
}

} // namespace WebCore

#endif // ENABLE(WEBGL)


text:
<!DOCTYPE html>

	<title>Grid Forms · Data entry made beautiful</title>
	<link rel="stylesheet" type="text/css" href="gridforms/gridforms.css">
	<link rel="stylesheet" type="text/css" href="media/style.css">

	<meta name="viewport" content="initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=no">

Data entry can be beautiful

Grid forms are dense forms designed for use in applications that require lots of data to be entered regularly. A tiny Javascript/CSS framework that helps you make forms on grids with ease.

Download on Github

  Tweet

	<form class="my-grid-form">
		<fieldset>
			<legend>Add to inventory</legend>

					Product Name
					<input type="text" id= "ProductName" autofocus>

					Tags
					<input id="tags" type="text">

					Vendor
					<select id="vendor">
						<option>Select a vendor</option>
						<option>ted</option>
						<option>Magna Phasellus Dolor Incorporated</option>
						<option>Fames Ac Turpis Inc.</option>
						<option>Eu Eros Institute</option>
						<option>Suspendisse Sagittis Associates</option>
						<option>Tempor Lorem PC</option>
						<option>Nulla Facilisi Sed PC</option>
						<option>Dignissim Corp.</option>
						<option>Blandit Ltd</option>
						<option>Dapibus Gravida Aliquam LLP</option>
						<option>Cursus A Inc.</option>
						<option>Tellus PC</option>
						<option>Fusce Mi Foundation</option>
						<option>Dictum Sapien Aenean Associates</option>
						<option>In Tincidunt PC</option>
						<option>Sapien Aenean Ltd</option>
						<option>Libero Foundation</option>
						<option>Egestas Rhoncus Proin Corp.</option>
						<option>Feugiat Nec Diam Institute</option>
						<option>Turpis Foundation</option>
						<option>Pede Malesuada Vel Associates</option>
						<option>Eget Venenatis A PC</option>
						<option>Mollis Vitae Corporation</option>
						<option>Gravida Mauris Incorporated</option>
						<option>Tortor Consulting</option>
						<option>Habitant Morbi Tristique Corporation</option>
						<option>Enim Corp.</option>
						<option>Sed Turpis Nec LLC</option>
						<option>Enim Foundation</option>
						<option>Tincidunt Orci Quis Institute</option>
						<option>Lectus Pede LLC</option>
						<option>Class Corporation</option>
						<option>Erat Volutpat Nulla LLP</option>
						<option>Sed LLC</option>
						<option>Justo Faucibus Associates</option>
						<option>Vel Turpis Foundation</option>
						<option>Tellus Aenean Limited</option>
						<option>Tempus Scelerisque Corporation</option>
						<option>Eleifend LLP</option>
						<option>A Felis Ullamcorper Company</option>
						<option>Neque Non LLC</option>
						<option>Nibh Donec Est PC</option>
					</select>

					Product Type
					<select id="productType">
						<option>Select a product type</option>
						<option>et magnis</option>
						<option>Vivamus rhoncus.</option>
						<option>egestas ligula.</option>
						<option>nulla. Cras</option>
						<option>Proin mi.</option>
						<option>turpis non</option>
						<option>ante ipsum</option>
						<option>arcu. Curabitur</option>
						<option>ante. Maecenas</option>
						<option>magna. Phasellus</option>
						<option>Suspendisse aliquet,</option>
						<option>purus gravida</option>
						<option>ac risus.</option>
						<option>mollis non,</option>
					</select>

					Product Description
					<textarea id="productDescription"></textarea>

					SKU
					<input type="text" id="sku">

					Initial Stock Level
					<input type="text" id="initialStockLevel">

					Cost Price
					<input type="text" id="costPrice">

					Wholesale Price
					<input type="text" id="wholesalePrive">

					Retail Price
					<input type="text" id="retailPrice">

		</fieldset>
	</form>

							Country
							<input type="text" id="country">

							City
							<input type="text" id="city">

1.Proximity of fields relative to each other on the grid provides useful context. And field sizes serve as hints for what the value might be.

2.With grid forms, lengthy forms can easily fit above the fold. Which means less scrolling. And tabbing through the form comes more naturally. Example Bank Application

3.Each field wraps to its own line on mobile devices. Even then, the forms are denser than their counterparts.

		Gridforms was made by Kumail Hunaid.

Follow @kumailht on Twitter or
subscribe to be notified about future projects.


text:
package com.topview.dao.interactivezone;

import com.topview.BaseTest;
import com.topview.common.Page;
import com.topview.po.interactivezone.Survey;
import org.junit.Assert;
import org.junit.Test;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

public class SurveyDaoTest extends BaseTest {

    @Resource
    private SurveyDao surveyDao;

    @Test
    public void testInsertSurvey() {
        Survey survey = new Survey();
        survey.setTitle("test");
        survey.setFaceUser(3);
        survey.setCreatorId(1L);
        survey.setQuNum(0);
        survey.setCreatedTime(new Date());
        survey.setModifiedTime(new Date());
        survey.setDeadline(new Date());
        survey.setStatus(1);
        survey.setParticipantNum(0);
        int result = surveyDao.insert(survey);
//        Assert.assertEquals(1, result);
    }

    @Test
    public void testDeleteById() {
        int result = surveyDao.deleteById(4L);
//        Assert.assertEquals(1, result);
    }

    @Test
    public void testSelectOneById() {
        Survey survey = surveyDao.selectOneById(4L);
        System.out.println(survey);
    }

    @Test
    public void testUpdate() {
        Survey survey = surveyDao.selectOneById(7L);
        survey.setTitle("test2");
        survey.setFaceUser(1);
        survey.setCreatedTime(new Date());
        survey.setDeadline(new Date());
        survey.setParticipantNum(1);
        survey.setQuNum(2);
        survey.setStatus(0);
        int result = surveyDao.update(survey);
        System.out.println(surveyDao.selectOneById(7L));
//        Assert.assertEquals(1, result);
    }

    @Test
    public void testSelect() {
        Survey survey = new Survey();
        survey.setCreatorId(1L);
        survey.setTitle("test");
        survey.setParticipantNum(0);
        survey.setStatus(1);
        survey.setFaceUser(3);
        survey.setQuNum(0);
        survey.setCreatorId(1L);
        survey.setId(4L);
        List<Survey> list = surveyDao.select(survey);
        System.out.println(list);
    }

    @Test
    public void testSelectPage() {
        System.out.println(surveyDao.getTotal(new Survey()));
        Page page = new Page(1, Integer.valueOf(surveyDao.getTotal(new Survey())));
        Survey survey = new Survey();
        survey.setTitle("test");
        List<Survey> list = surveyDao.selectPage(survey, page);
        System.out.println(list);
    }

    @Test
    public void testInsertAnswerRecord() {
        int result = surveyDao.insertAnswerRecord(1L, 4L);
//        Assert.assertEquals(result ,1);
    }

    @Test
    public void testSelectAnswerRecord() {
        int result = surveyDao.selectAnswerRecord(1L, 4L);
        System.out.println(result);
    }
}


text:
from __future__ import unicode_literals, division, print_function, absolute_import

class Error(Exception):
    """all prom errors will inherit from this base class"""
    def __init__(self, e, exc_info=None):
        self.e = e
        self.exc_info = exc_info
        super(Error, self).__init__(str(e))

class InterfaceError(Error):
    """specifically for wrapping SQLite and Postgres errors"""
    pass

class UniqueError(InterfaceError):
    pass


text:
/*
 * Three environment variables are used by the parsing routines:
 *
 * 'partition' - keeps current partition identifier
 *
 * partition  := <part-id>
 * <part-id>  := <dev-id>,part_num
 *
 *
 * 'mtdids' - linux kernel mtd device id <-> u-boot device id mapping
 *
 * mtdids=<idmap>[,<idmap>,...]
 *
 * <idmap>    := <dev-id>=<mtd-id>
 * <dev-id>   := 'nand'|'nor'<dev-num>
 * <dev-num>  := mtd device number, 0...
 * <mtd-id>   := unique device tag used by linux kernel to find mtd device (mtd->name)
 *
 *
 * 'mtdparts' - partition list
 *
 * mtdparts=mtdparts=<mtd-def>[;<mtd-def>...]
 *
 * <mtd-def>  := <mtd-id>:<part-def>[,<part-def>...]
 * <mtd-id>   := unique device tag used by linux kernel to find mtd device (mtd->name)
 * <part-def> := <size>[@<offset>][<name>][<ro-flag>]
 * <size>     := standard linux memsize OR '-' to denote all remaining space
 * <offset>   := partition start offset within the device
 * <name>     := '(' NAME ')'
 * <ro-flag>  := when set to 'ro' makes partition read-only (not used, passed to kernel)
 *
 * Notes:
 * - each <mtd-id> used in mtdparts must albo exist in 'mtddis' mapping
 * - if the above variables are not set defaults for a given target are used
 *
 * Examples:
 *
 * 1 NOR Flash, with 1 single writable partition:
 * mtdids=nor0=edb7312-nor
 * mtdparts=mtdparts=edb7312-nor:-
 *
 * 1 NOR Flash with 2 partitions, 1 NAND with one
 * mtdids=nor0=edb7312-nor,nand0=edb7312-nand
 * mtdparts=mtdparts=edb7312-nor:256k(ARMboot)ro,-(root);edb7312-nand:-(home)
 *
 */

/*
 * JFFS2/CRAMFS support
 */
#include <common.h>
#include <command.h>
#include <malloc.h>
#include <jffs2/jffs2.h>
#include <linux/list.h>
#include <linux/ctype.h>

#if (CONFIG_COMMANDS & CFG_CMD_JFFS2)

#include <cramfs/cramfs_fs.h>

#if (CONFIG_COMMANDS & CFG_CMD_NAND)
#ifdef CFG_NAND_LEGACY
#include <linux/mtd/nand_legacy.h>
#else /* !CFG_NAND_LEGACY */
#include <linux/mtd/nand.h>
#include <nand.h>
#endif /* !CFG_NAND_LEGACY */
#endif /* (CONFIG_COMMANDS & CFG_CMD_NAND) */
/* enable/disable debugging messages */
#define	DEBUG_JFFS
#undef	DEBUG_JFFS

#ifdef  DEBUG_JFFS
# define DEBUGF(fmt, args...)	printf(fmt ,##args)
#else
# define DEBUGF(fmt, args...)
#endif

/* special size referring to all the remaining space in a partition */
#define SIZE_REMAINING		0xFFFFFFFF

/* special offset value, it is used when not provided by user
 *
 * this value is used temporarily during parsing, later such offests
 * are recalculated */
#define OFFSET_NOT_SPECIFIED	0xFFFFFFFF

/* minimum partition size */
#define MIN_PART_SIZE		4096

/* this flag needs to be set in part_info struct mask_flags
 * field for read-only partitions */
#define MTD_WRITEABLE_CMD		1

#ifdef CONFIG_JFFS2_CMDLINE
/* default values for mtdids and mtdparts variables */
#if defined(MTDIDS_DEFAULT)
static const char *const mtdids_default = MTDIDS_DEFAULT;
#else
#warning "MTDIDS_DEFAULT not defined!"
static const char *const mtdids_default = NULL;
#endif

extern char bLARGEBLOCK;			//HJ_add 20090807
extern char b128MB;				//HJ_add 20090807
#if defined(MTDPARTS_DEFAULT)
static const char *const mtdparts_default = MTDPARTS_DEFAULT;
#else
#warning "MTDPARTS_DEFAULT not defined!"
static const char *const mtdparts_default = NULL;
#endif

/* copies of last seen 'mtdids', 'mtdparts' and 'partition' env variables */
#define MTDIDS_MAXLEN		128
#define MTDPARTS_MAXLEN		512
#define PARTITION_MAXLEN	16
static char last_ids[MTDIDS_MAXLEN];
static char last_parts[MTDPARTS_MAXLEN];
static char last_partition[PARTITION_MAXLEN];

/* low level jffs2 cache cleaning routine */
extern void jffs2_free_cache(struct part_info *part);

/* mtdids mapping list, filled by parse_ids() */
struct list_head mtdids;

/* device/partition list, parse_cmdline() parses into here */
struct list_head devices;
#endif /* #ifdef CONFIG_JFFS2_CMDLINE */

/* current active device and partition number */
static struct mtd_device *current_dev = NULL;
static u8 current_partnum = 0;

extern int cramfs_check (struct part_info *info);
extern int cramfs_load (char *loadoffset, struct part_info *info, char *filename);
extern int cramfs_ls (struct part_info *info, char *filename);
extern int cramfs_info (struct part_info *info);

static struct part_info* jffs2_part_info(struct mtd_device *dev, unsigned int part_num);

/* command line only routines */
#ifdef CONFIG_JFFS2_CMDLINE

static struct mtdids* id_find_by_mtd_id(const char *mtd_id, unsigned int mtd_id_len);
static int device_del(struct mtd_device *dev);

/**
 * Parses a string into a number.  The number stored at ptr is
 * potentially suffixed with K (for kilobytes, or 1024 bytes),
 * M (for megabytes, or 1048576 bytes), or G (for gigabytes, or
 * 1073741824).  If the number is suffixed with K, M, or G, then
 * the return value is the number multiplied by one kilobyte, one
 * megabyte, or one gigabyte, respectively.
 *
 * @param ptr where parse begins
 * @param retptr output pointer to next char after parse completes (output)
 * @return resulting unsigned int
 */
static unsigned long memsize_parse (const char *const ptr, const char **retptr)
{
	unsigned long ret = simple_strtoul(ptr, (char **)retptr, 0);

	switch (**retptr) {
		case 'G':
		case 'g':
			ret <<= 10;
		case 'M':
		case 'm':
			ret <<= 10;
		case 'K':
		case 'k':
			ret <<= 10;
			(*retptr)++;
		default:
			break;
	}

	return ret;
}

/**
 * Format string describing supplied size. This routine does the opposite job
 * to memsize_parse(). Size in bytes is converted to string and if possible
 * shortened by using k (kilobytes), m (megabytes) or g (gigabytes) suffix.
 *
 * Note, that this routine does not check for buffer overflow, it's the caller
 * who must assure enough space.
 *
 * @param buf output buffer
 * @param size size to be converted to string
 */
static void memsize_format(char *buf, u32 size)
{
#define SIZE_GB ((u32)1024*1024*1024)
#define SIZE_MB ((u32)1024*1024)
#define SIZE_KB ((u32)1024)

	if ((size % SIZE_GB) == 0)
		sprintf(buf, "%lug", size/SIZE_GB);
	else if ((size % SIZE_MB) == 0)
		sprintf(buf, "%lum", size/SIZE_MB);
	else if (size % SIZE_KB == 0)
		sprintf(buf, "%luk", size/SIZE_KB);
	else
		sprintf(buf, "%lu", size);
}

/**
 * This routine does global indexing of all partitions. Resulting index for
 * current partition is saved in 'mtddevnum'. Current partition name in
 * 'mtddevname'.
 */
static void index_partitions(void)
{
	char buf[16];
	u16 mtddevnum;
	struct part_info *part;
	struct list_head *dentry;
	struct mtd_device *dev;

	DEBUGF("--- index partitions ---\n");

	if (current_dev) {
		mtddevnum = 0;
		list_for_each(dentry, &devices) {
			dev = list_entry(dentry, struct mtd_device, link);
			if (dev == current_dev) {
				mtddevnum += current_partnum;
				sprintf(buf, "%d", mtddevnum);
				setenv("mtddevnum", buf);
				break;
			}
			mtddevnum += dev->num_parts;
		}

		part = jffs2_part_info(current_dev, current_partnum);
		setenv("mtddevname", part->name);

		DEBUGF("=> mtddevnum %d,\n=> mtddevname %s\n", mtddevnum, part->name);
	} else {
		setenv("mtddevnum", NULL);
		setenv("mtddevname", NULL);

		DEBUGF("=> mtddevnum NULL\n=> mtddevname NULL\n");
	}
}

/**
 * Save current device and partition in environment variable 'partition'.
 */
static void current_save(void)
{
	char buf[16];

	DEBUGF("--- current_save ---\n");

	if (current_dev) {
		sprintf(buf, "%s%d,%d", MTD_DEV_TYPE(current_dev->id->type),
					current_dev->id->num, current_partnum);

		setenv("partition", buf);
		strncpy(last_partition, buf, 16);

		DEBUGF("=> partition %s\n", buf);
	} else {
		setenv("partition", NULL);
		last_partition[0] = '\0';

		DEBUGF("=> partition NULL\n");
	}
	index_partitions();
}

/**
 * Performs sanity check for supplied NOR flash partition. Table of existing
 * NOR flash devices is searched and partition device is located. Alignment
 * with the granularity of NOR flash sectors is verified.
 *
 * @param id of the parent device
 * @param part partition to validate
 * @return 0 if partition is valid, 1 otherwise
 */
static int part_validate_nor(struct mtdids *id, struct part_info *part)
{
#if (CONFIG_COMMANDS & CFG_CMD_FLASH)
	/* info for FLASH chips */
	extern flash_info_t flash_info[];
	flash_info_t *flash;
	int offset_aligned;
	u32 end_offset;
	int i;

	flash = &flash_info[id->num];

	offset_aligned = 0;
	for (i = 0; i < flash->sector_count; i++) {
		if ((flash->start[i] - flash->start[0]) == part->offset) {
			offset_aligned = 1;
			break;
		}
	}
	if (offset_aligned == 0) {
		printf("%s%d: partition (%s) start offset alignment incorrect\n",
				MTD_DEV_TYPE(id->type), id->num, part->name);
		return 1;
	}

	end_offset = part->offset + part->size;
	for (i = 0; i < flash->sector_count; i++) {
		if ((flash->start[i] - flash->start[0]) == end_offset)
			return 0;
	}

	if (flash->size == end_offset)
		return 0;

	printf("%s%d: partition (%s) size alignment incorrect\n",
			MTD_DEV_TYPE(id->type), id->num, part->name);
#endif
	return 1;
}

/**
 * Performs sanity check for supplied NAND flash partition. Table of existing
 * NAND flash devices is searched and partition device is located. Alignment
 * with the granularity of nand erasesize is verified.
 *
 * @param id of the parent device
 * @param part partition to validate
 * @return 0 if partition is valid, 1 otherwise
 */
static int part_validate_nand(struct mtdids *id, struct part_info *part)
{
#if defined(CONFIG_JFFS2_NAND) && (CONFIG_COMMANDS & CFG_CMD_NAND)
	/* info for NAND chips */
	nand_info_t *nand;

	nand = &nand_info[id->num];

	if ((unsigned long)(part->offset) % nand->erasesize) {
		printf("%s%d: partition (%s) start offset alignment incorrect\n",
				MTD_DEV_TYPE(id->type), id->num, part->name);
		return 1;
	}

	if (part->size % nand->erasesize) {
		printf("%s%d: partition (%s) size alignment incorrect\n",
				MTD_DEV_TYPE(id->type), id->num, part->name);
		return 1;
	}

	return 0;
#else
	return 1;
#endif
}

/**
 * Performs sanity check for supplied partition. Offset and size are verified
 * to be within valid range. Partition type is checked and either
 * parts_validate_nor() or parts_validate_nand() is called with the argument
 * of part.
 *
 * @param id of the parent device
 * @param part partition to validate
 * @return 0 if partition is valid, 1 otherwise
 */
static int part_validate(struct mtdids *id, struct part_info *part)
{
	if (part->size == SIZE_REMAINING)
		part->size = id->size - part->offset;

	if (part->offset > id->size) {
		printf("%s: offset %08lx beyond flash size %08lx\n",
				id->mtd_id, part->offset, id->size);
		return 1;
	}

	if ((part->offset + part->size) <= part->offset) {
		printf("%s%d: partition (%s) size too big\n",
				MTD_DEV_TYPE(id->type), id->num, part->name);
		return 1;
	}

	if (part->offset + part->size > id->size) {
		printf("%s: partitioning exceeds flash size\n", id->mtd_id);
		return 1;
	}

	if (id->type == MTD_DEV_TYPE_NAND)
		return part_validate_nand(id, part);
	else if (id->type == MTD_DEV_TYPE_NOR)
		return part_validate_nor(id, part);
	else
		DEBUGF("part_validate: invalid dev type\n");

	return 1;
}

/**
 * Delete selected partition from the partion list of the specified device.
 *
 * @param dev device to delete partition from
 * @param part partition to delete
 * @return 0 on success, 1 otherwise
 */
static int part_del(struct mtd_device *dev, struct part_info *part)
{
	u8 current_save_needed = 0;

	/* if there is only one partition, remove whole device */
	if (dev->num_parts == 1)
		return device_del(dev);

	/* otherwise just delete this partition */

	if (dev == current_dev) {
		/* we are modyfing partitions for the current device,
		 * update current */
		struct part_info *curr_pi;
		curr_pi = jffs2_part_info(current_dev, current_partnum);

		if (curr_pi) {
			if (curr_pi == part) {
				printf("current partition deleted, resetting current to 0\n");
				current_partnum = 0;
			} else if (part->offset <= curr_pi->offset) {
				current_partnum--;
			}
			current_save_needed = 1;
		}
	}

#ifdef CFG_NAND_LEGACY
	jffs2_free_cache(part);
#endif
	list_del(&part->link);
	free(part);
	dev->num_parts--;

	if (current_save_needed > 0)
		current_save();
	else
		index_partitions();

	return 0;
}

/**
 * Delete all partitions from parts head list, free memory.
 *
 * @param head list of partitions to delete
 */
static void part_delall(struct list_head *head)
{
	struct list_head *entry, *n;
	struct part_info *part_tmp;

	/* clean tmp_list and free allocated memory */
	list_for_each_safe(entry, n, head) {
		part_tmp = list_entry(entry, struct part_info, link);

#ifdef CFG_NAND_LEGACY
		jffs2_free_cache(part_tmp);
#endif
		list_del(entry);
		free(part_tmp);
	}
}

/**
 * Add new partition to the supplied partition list. Make sure partitions are
 * sorted by offset in ascending order.
 *
 * @param head list this partition is to be added to
 * @param new partition to be added
 */
static int part_sort_add(struct mtd_device *dev, struct part_info *part)
{
	struct list_head *entry;
	struct part_info *new_pi, *curr_pi;

	/* link partition to parrent dev */
	part->dev = dev;

	if (list_empty(&dev->parts)) {
		DEBUGF("part_sort_add: list empty\n");
		list_add(&part->link, &dev->parts);
		dev->num_parts++;
		index_partitions();
		return 0;
	}

	new_pi = list_entry(&part->link, struct part_info, link);

	/* get current partition info if we are updating current device */
	curr_pi = NULL;
	if (dev == current_dev)
		curr_pi = jffs2_part_info(current_dev, current_partnum);

	list_for_each(entry, &dev->parts) {
		struct part_info *pi;

		pi = list_entry(entry, struct part_info, link);

		/* be compliant with kernel cmdline, allow only one partition at offset zero */
		if ((new_pi->offset == pi->offset) && (pi->offset == 0)) {
			printf("cannot add second partition at offset 0\n");
			return 1;
		}

		if (new_pi->offset <= pi->offset) {
			list_add_tail(&part->link, entry);
			dev->num_parts++;

			if (curr_pi && (pi->offset <= curr_pi->offset)) {
				/* we are modyfing partitions for the current
				 * device, update current */
				current_partnum++;
				current_save();
			} else {
				index_partitions();
			}
			return 0;
		}
	}

	list_add_tail(&part->link, &dev->parts);
	dev->num_parts++;
	index_partitions();
	return 0;
}

/**
 * Add provided partition to the partition list of a given device.
 *
 * @param dev device to which partition is added
 * @param part partition to be added
 * @return 0 on success, 1 otherwise
 */
static int part_add(struct mtd_device *dev, struct part_info *part)
{
	/* verify alignment and size */
	if (part_validate(dev->id, part) != 0)
		return 1;

	/* partition is ok, add it to the list */
	if (part_sort_add(dev, part) != 0)
		return 1;

	return 0;
}

/**
 * Parse one partition definition, allocate memory and return pointer to this
 * location in retpart.
 *
 * @param partdef pointer to the partition definition string i.e. <part-def>
 * @param ret output pointer to next char after parse completes (output)
 * @param retpart pointer to the allocated partition (output)
 * @return 0 on success, 1 otherwise
 */
static int part_parse(const char *const partdef, const char **ret, struct part_info **retpart)
{
	struct part_info *part;
	unsigned long size;
	unsigned long offset;
	const char *name;
	int name_len;
	unsigned int mask_flags;
	const char *p;

	p = partdef;
	*retpart = NULL;
	*ret = NULL;

	/* fetch the partition size */
	if (*p == '-') {
		/* assign all remaining space to this partition */
		DEBUGF("'-': remaining size assigned\n");
		size = SIZE_REMAINING;
		p++;
	} else {
		size = memsize_parse(p, &p);
		if (size < MIN_PART_SIZE) {
			printf("partition size too small (%lx)\n", size);
			return 1;
		}
	}

	/* check for offset */
	offset = OFFSET_NOT_SPECIFIED;
	if (*p == '@') {
		p++;
		offset = memsize_parse(p, &p);
	}

	/* now look for the name */
	if (*p == '(') {
		name = ++p;
		if ((p = strchr(name, ')')) == NULL) {
			printf("no closing ) found in partition name\n");
			return 1;
		}
		name_len = p - name + 1;
		if ((name_len - 1) == 0) {
			printf("empty partition name\n");
			return 1;
		}
		p++;
	} else {
		/* 0x00000000@0x00000000 */
		name_len = 22;
		name = NULL;
	}

	/* test for options */
	mask_flags = 0;
	if (strncmp(p, "ro", 2) == 0) {
		mask_flags |= MTD_WRITEABLE_CMD;
		p += 2;
	}

	/* check for next partition definition */
	if (*p == ',') {
		if (size == SIZE_REMAINING) {
			*ret = NULL;
			printf("no partitions allowed after a fill-up partition\n");
			return 1;
		}
		*ret = ++p;
	} else if ((*p == ';') || (*p == '\0')) {
		*ret = p;
	} else {
		printf("unexpected character '%c' at the end of partition\n", *p);
		*ret = NULL;
		return 1;
	}

	/*  allocate memory */
	part = (struct part_info *)malloc(sizeof(struct part_info) + name_len);
	if (!part) {
		printf("out of memory\n");
		return 1;
	}
	memset(part, 0, sizeof(struct part_info) + name_len);
	part->size = size;
	part->offset = offset;
	part->mask_flags = mask_flags;
	part->name = (char *)(part + 1);

	if (name) {
		/* copy user provided name */
		strncpy(part->name, name, name_len - 1);
		part->auto_name = 0;
	} else {
		/* auto generated name in form of size@offset */
		sprintf(part->name, "0x%08lx@0x%08lx", size, offset);
		part->auto_name = 1;
	}

	part->name[name_len - 1] = '\0';
	INIT_LIST_HEAD(&part->link);

	DEBUGF("+ partition: name %-22s size 0x%08x offset 0x%08x mask flags %d\n",
			part->name, part->size,
			part->offset, part->mask_flags);

	*retpart = part;
	return 0;
}
#endif/* #ifdef CONFIG_JFFS2_CMDLINE */

/**
 * Check device number to be within valid range for given device type.
 *
 * @param dev device to validate
 * @return 0 if device is valid, 1 otherwise
 */
static int device_validate(u8 type, u8 num, u32 *size)
{
	if (type == MTD_DEV_TYPE_NOR) {
#if (CONFIG_COMMANDS & CFG_CMD_FLASH)
		if (num < CFG_MAX_FLASH_BANKS) {
			extern flash_info_t flash_info[];
			*size = flash_info[num].size;

			return 0;
		}

		printf("no such FLASH device: %s%d (valid range 0 ... %d\n",
				MTD_DEV_TYPE(type), num, CFG_MAX_FLASH_BANKS - 1);
#else
		printf("support for FLASH devices not present\n");
#endif
	} else if (type == MTD_DEV_TYPE_NAND) {
#if defined(CONFIG_JFFS2_NAND) && (CONFIG_COMMANDS & CFG_CMD_NAND)
		if (num < CFG_MAX_NAND_DEVICE) {
#ifndef CFG_NAND_LEGACY
			*size = nand_info[num].size;
#else
			extern struct nand_chip nand_dev_desc[CFG_MAX_NAND_DEVICE];
			*size = nand_dev_desc[num].totlen;
#endif
			return 0;
		}

		printf("no such NAND device: %s%d (valid range 0 ... %d)\n",
				MTD_DEV_TYPE(type), num, CFG_MAX_NAND_DEVICE - 1);
#else
		printf("support for NAND devices not present\n");
#endif
	}

	return 1;
}

#ifdef CONFIG_JFFS2_CMDLINE
/**
 * Delete all mtd devices from a supplied devices list, free memory allocated for
 * each device and delete all device partitions.
 *
 * @return 0 on success, 1 otherwise
 */
static int device_delall(struct list_head *head)
{
	struct list_head *entry, *n;
	struct mtd_device *dev_tmp;

	/* clean devices list */
	list_for_each_safe(entry, n, head) {
		dev_tmp = list_entry(entry, struct mtd_device, link);
		list_del(entry);
		part_delall(&dev_tmp->parts);
		free(dev_tmp);
	}
	INIT_LIST_HEAD(&devices);

	return 0;
}

/**
 * If provided device exists it's partitions are deleted, device is removed
 * from device list and device memory is freed.
 *
 * @param dev device to be deleted
 * @return 0 on success, 1 otherwise
 */
static int device_del(struct mtd_device *dev)
{
	part_delall(&dev->parts);
	list_del(&dev->link);
	free(dev);

	if (dev == current_dev) {
		/* we just deleted current device */
		if (list_empty(&devices)) {
			current_dev = NULL;
		} else {
			/* reset first partition from first dev from the
			 * devices list as current */
			current_dev = list_entry(devices.next, struct mtd_device, link);
			current_partnum = 0;
		}
		current_save();
		return 0;
	}

	index_partitions();
	return 0;
}

/**
 * Search global device list and return pointer to the device of type and num
 * specified.
 *
 * @param type device type
 * @param num device number
 * @return NULL if requested device does not exist
 */
static struct mtd_device* device_find(u8 type, u8 num)
{
	struct list_head *entry;
	struct mtd_device *dev_tmp;

	list_for_each(entry, &devices) {
		dev_tmp = list_entry(entry, struct mtd_device, link);

		if ((dev_tmp->id->type == type) && (dev_tmp->id->num == num))
			return dev_tmp;
	}

	return NULL;
}

/**
 * Add specified device to the global device list.
 *
 * @param dev device to be added
 */
static void device_add(struct mtd_device *dev)
{
	u8 current_save_needed = 0;

	if (list_empty(&devices)) {
		current_dev = dev;
		current_partnum = 0;
		current_save_needed = 1;
	}

	list_add_tail(&dev->link, &devices);

	if (current_save_needed > 0)
		current_save();
	else
		index_partitions();
}

/**
 * Parse device type, name and mtd-id. If syntax is ok allocate memory and
 * return pointer to the device structure.
 *
 * @param mtd_dev pointer to the device definition string i.e. <mtd-dev>
 * @param ret output pointer to next char after parse completes (output)
 * @param retdev pointer to the allocated device (output)
 * @return 0 on success, 1 otherwise
 */
static int device_parse(const char *const mtd_dev, const char **ret, struct mtd_device **retdev)
{
	struct mtd_device *dev;
	struct part_info *part;
	struct mtdids *id;
	const char *mtd_id;
	unsigned int mtd_id_len;
	const char *p, *pend;
	LIST_HEAD(tmp_list);
	struct list_head *entry, *n;
	u16 num_parts;
	u32 offset;
	int err = 1;

	p = mtd_dev;
	*retdev = NULL;
	*ret = NULL;

	DEBUGF("===device_parse===\n");

	/* fetch <mtd-id> */
	mtd_id = p;
	if (!(p = strchr(mtd_id, ':'))) {
		printf("no <mtd-id> identifier\n");
		return 1;
	}
	mtd_id_len = p - mtd_id + 1;
	p++;

	/* verify if we have a valid device specified */
	if ((id = id_find_by_mtd_id(mtd_id, mtd_id_len - 1)) == NULL) {
		printf("invalid mtd device '%.*s'\n", mtd_id_len - 1, mtd_id);
		return 1;
	}

	DEBUGF("dev type = %d (%s), dev num = %d, mtd-id = %s\n",
			id->type, MTD_DEV_TYPE(id->type),
			id->num, id->mtd_id);
	pend = strchr(p, ';');
	DEBUGF("parsing partitions %.*s\n", (pend ? pend - p : strlen(p)), p);

	/* parse partitions */
	num_parts = 0;

	offset = 0;
	if ((dev = device_find(id->type, id->num)) != NULL) {
		/* if device already exists start at the end of the last partition */
		part = list_entry(dev->parts.prev, struct part_info, link);
		offset = part->offset + part->size;
	}

	while (p && (*p != '\0') && (*p != ';')) {
		err = 1;
		if ((part_parse(p, &p, &part) != 0) || (!part))
			break;

		/* calculate offset when not specified */
		if (part->offset == OFFSET_NOT_SPECIFIED)
			part->offset = offset;
		else
			offset = part->offset;

		/* verify alignment and size */
		if (part_validate(id, part) != 0)
			break;

		offset += part->size;

		/* partition is ok, add it to the list */
		list_add_tail(&part->link, &tmp_list);
		num_parts++;
		err = 0;
	}
	if (err == 1) {
		part_delall(&tmp_list);
		return 1;
	}

	if (num_parts == 0) {
		printf("no partitions for device %s%d (%s)\n",
				MTD_DEV_TYPE(id->type), id->num, id->mtd_id);
		return 1;
	}

	DEBUGF("\ntotal partitions: %d\n", num_parts);

	/* check for next device presence */
	if (p) {
		if (*p == ';') {
			*ret = ++p;
		} else if (*p == '\0') {
			*ret = p;
		} else {
			printf("unexpected character '%c' at the end of device\n", *p);
			*ret = NULL;
			return 1;
		}
	}

	/* allocate memory for mtd_device structure */
	if ((dev = (struct mtd_device *)malloc(sizeof(struct mtd_device))) == NULL) {
		printf("out of memory\n");
		return 1;
	}
	memset(dev, 0, sizeof(struct mtd_device));
	dev->id = id;
	dev->num_parts = 0; /* part_sort_add increments num_parts */
	INIT_LIST_HEAD(&dev->parts);
	INIT_LIST_HEAD(&dev->link);

	/* move partitions from tmp_list to dev->parts */
	list_for_each_safe(entry, n, &tmp_list) {
		part = list_entry(entry, struct part_info, link);
		list_del(entry);
		if (part_sort_add(dev, part) != 0) {
			device_del(dev);
			return 1;
		}
	}

	*retdev = dev;

	DEBUGF("===\n\n");
	return 0;
}

/**
 * Initialize global device list.
 *
 * @return 0 on success, 1 otherwise
 */
static int devices_init(void)
{
	last_parts[0] = '\0';
	current_dev = NULL;
	current_save();

	return device_delall(&devices);
}

/*
 * Search global mtdids list and find id of requested type and number.
 *
 * @return pointer to the id if it exists, NULL otherwise
 */
static struct mtdids* id_find(u8 type, u8 num)
{
	struct list_head *entry;
	struct mtdids *id;

	list_for_each(entry, &mtdids) {
		id = list_entry(entry, struct mtdids, link);

		if ((id->type == type) && (id->num == num))
			return id;
	}

	return NULL;
}

/**
 * Search global mtdids list and find id of a requested mtd_id.
 *
 * Note: first argument is not null terminated.
 *
 * @param mtd_id string containing requested mtd_id
 * @param mtd_id_len length of supplied mtd_id
 * @return pointer to the id if it exists, NULL otherwise
 */
static struct mtdids* id_find_by_mtd_id(const char *mtd_id, unsigned int mtd_id_len)
{
	struct list_head *entry;
	struct mtdids *id;

	DEBUGF("--- id_find_by_mtd_id: '%.*s' (len = %d)\n",
			mtd_id_len, mtd_id, mtd_id_len);

	list_for_each(entry, &mtdids) {
		id = list_entry(entry, struct mtdids, link);

		DEBUGF("entry: '%s' (len = %d)\n",
				id->mtd_id, strlen(id->mtd_id));

		if (mtd_id_len != strlen(id->mtd_id))
			continue;
		if (strncmp(id->mtd_id, mtd_id, mtd_id_len) == 0)
			return id;
	}

	return NULL;
}
#endif /* #ifdef CONFIG_JFFS2_CMDLINE */

/**
 * Parse device id string <dev-id> := 'nand'|'nor'<dev-num>, return device
 * type and number.
 *
 * @param id string describing device id
 * @param ret_id output pointer to next char after parse completes (output)
 * @param dev_type parsed device type (output)
 * @param dev_num parsed device number (output)
 * @return 0 on success, 1 otherwise
 */
int id_parse(const char *id, const char **ret_id, u8 *dev_type, u8 *dev_num)
{
	const char *p = id;

	*dev_type = 0;
	if (strncmp(p, "nand", 4) == 0) {
		*dev_type = MTD_DEV_TYPE_NAND;
		p += 4;
	} else if (strncmp(p, "nor", 3) == 0) {
		*dev_type = MTD_DEV_TYPE_NOR;
		p += 3;
	} else {
		printf("incorrect device type in %s\n", id);
		return 1;
	}

	if (!isdigit(*p)) {
		printf("incorrect device number in %s\n", id);
		return 1;
	}

	*dev_num = simple_strtoul(p, (char **)&p, 0);
	if (ret_id)
		*ret_id = p;
	return 0;
}

#ifdef CONFIG_JFFS2_CMDLINE
/**
 * Process all devices and generate corresponding mtdparts string describing
 * all partitions on all devices.
 *
 * @param buf output buffer holding generated mtdparts string (output)
 * @param buflen buffer size
 * @return 0 on success, 1 otherwise
 */
static int generate_mtdparts(char *buf, u32 buflen)
{
	struct list_head *pentry, *dentry;
	struct mtd_device *dev;
	struct part_info *part, *prev_part;
	char *p = buf;
	char tmpbuf[32];
	u32 size, offset, len, part_cnt;
	u32 maxlen = buflen - 1;

	DEBUGF("--- generate_mtdparts ---\n");

	if (list_empty(&devices)) {
		buf[0] = '\0';
		return 0;
	}

	sprintf(p, "mtdparts=");
	p += 9;

	list_for_each(dentry, &devices) {
		dev = list_entry(dentry, struct mtd_device, link);

		/* copy mtd_id */
		len = strlen(dev->id->mtd_id) + 1;
		if (len > maxlen)
			goto cleanup;
		memcpy(p, dev->id->mtd_id, len - 1);
		p += len - 1;
		*(p++) = ':';
		maxlen -= len;

		/* format partitions */
		prev_part = NULL;
		part_cnt = 0;
		list_for_each(pentry, &dev->parts) {
			part = list_entry(pentry, struct part_info, link);
			size = part->size;
			offset = part->offset;
			part_cnt++;

			/* partition size */
			memsize_format(tmpbuf, size);
			len = strlen(tmpbuf);
			if (len > maxlen)
				goto cleanup;
			memcpy(p, tmpbuf, len);
			p += len;
			maxlen -= len;

			/* add offset only when there is a gap between
			 * partitions */
			if ((!prev_part && (offset != 0)) ||
					(prev_part && ((prev_part->offset + prev_part->size) != part->offset))) {

				memsize_format(tmpbuf, offset);
				len = strlen(tmpbuf) + 1;
				if (len > maxlen)
					goto cleanup;
				*(p++) = '@';
				memcpy(p, tmpbuf, len - 1);
				p += len - 1;
				maxlen -= len;
			}

			/* copy name only if user supplied */
			if(!part->auto_name) {
				len = strlen(part->name) + 2;
				if (len > maxlen)
					goto cleanup;

				*(p++) = '(';
				memcpy(p, part->name, len - 2);
				p += len - 2;
				*(p++) = ')';
				maxlen -= len;
			}

			/* ro mask flag */
			if (part->mask_flags && MTD_WRITEABLE_CMD) {
				len = 2;
				if (len > maxlen)
					goto cleanup;
				*(p++) = 'r';
				*(p++) = 'o';
				maxlen -= 2;
			}

			/* print ',' separator if there are other partitions
			 * following */
			if (dev->num_parts > part_cnt) {
				if (1 > maxlen)
					goto cleanup;
				*(p++) = ',';
				maxlen--;
			}
			prev_part = part;
		}
		/* print ';' separator if there are other devices following */
		if (dentry->next != &devices) {
			if (1 > maxlen)
				goto cleanup;
			*(p++) = ';';
			maxlen--;
		}
	}

	/* we still have at least one char left, as we decremented maxlen at
	 * the begining */
	*p = '\0';

	return 0;

cleanup:
	last_parts[0] = '\0';
	return 1;
}

/**
 * Call generate_mtdparts to process all devices and generate corresponding
 * mtdparts string, save it in mtdparts environment variable.
 *
 * @param buf output buffer holding generated mtdparts string (output)
 * @param buflen buffer size
 * @return 0 on success, 1 otherwise
 */
static int generate_mtdparts_save(char *buf, u32 buflen)
{
	int ret;

	ret = generate_mtdparts(buf, buflen);

	if ((buf[0] != '\0') && (ret == 0))
		setenv("mtdparts", buf);
	else
		setenv("mtdparts", NULL);

	return ret;
}

/**
 * Format and print out a partition list for each device from global device
 * list.
 */
static void list_partitions(void)
{
	struct list_head *dentry, *pentry;
	struct part_info *part;
	struct mtd_device *dev;
	int part_num;

	DEBUGF("\n---list_partitions---\n");
	list_for_each(dentry, &devices) {
		dev = list_entry(dentry, struct mtd_device, link);
		printf("\ndevice %s%d <%s>, # parts = %d\n",
				MTD_DEV_TYPE(dev->id->type), dev->id->num,
				dev->id->mtd_id, dev->num_parts);
		printf(" #: name\t\t\tsize\t\toffset\t\tmask_flags\n");

		/* list partitions for given device */
		part_num = 0;
		list_for_each(pentry, &dev->parts) {
			part = list_entry(pentry, struct part_info, link);
			printf("%2d: %-20s0x%08x\t0x%08x\t%d\n",
					part_num, part->name, part->size,
					part->offset, part->mask_flags);

			part_num++;
		}
	}
	if (list_empty(&devices))
		printf("no partitions defined\n");

	/* current_dev is not NULL only when we have non empty device list */
	if (current_dev) {
		part = jffs2_part_info(current_dev, current_partnum);
		if (part) {
			printf("\nactive partition: %s%d,%d - (%s) 0x%08lx @ 0x%08lx\n",
					MTD_DEV_TYPE(current_dev->id->type),
					current_dev->id->num, current_partnum,
					part->name, part->size, part->offset);
		} else {
			printf("could not get current partition info\n\n");
		}
	}

	printf("\ndefaults:\n");
	printf("mtdids  : %s\n", mtdids_default);
	printf("mtdparts: %s\n", mtdparts_default);
}

/**
 * Given partition identifier in form of <dev_type><dev_num>,<part_num> find
 * corresponding device and verify partition number.
 *
 * @param id string describing device and partition or partition name
 * @param dev pointer to the requested device (output)
 * @param part_num verified partition number (output)
 * @param part pointer to requested partition (output)
 * @return 0 on success, 1 otherwise
 */
int find_dev_and_part(const char *id, struct mtd_device **dev,
		u8 *part_num, struct part_info **part)
{
	struct list_head *dentry, *pentry;
	u8 type, dnum, pnum;
	const char *p;

	DEBUGF("--- find_dev_and_part ---\nid = %s\n", id);

	list_for_each(dentry, &devices) {
		*part_num = 0;
		*dev = list_entry(dentry, struct mtd_device, link);
		list_for_each(pentry, &(*dev)->parts) {
			*part = list_entry(pentry, struct part_info, link);
			if (strcmp((*part)->name, id) == 0)
				return 0;
			(*part_num)++;
		}
	}

	p = id;
	*dev = NULL;
	*part = NULL;
	*part_num = 0;

	if (id_parse(p, &p, &type, &dnum) != 0)
		return 1;

	if ((*p++ != ',') || (*p == '\0')) {
		printf("no partition number specified\n");
		return 1;
	}
	pnum = simple_strtoul(p, (char **)&p, 0);
	if (*p != '\0') {
		printf("unexpected trailing character '%c'\n", *p);
		return 1;
	}

	if ((*dev = device_find(type, dnum)) == NULL) {
		printf("no such device %s%d\n", MTD_DEV_TYPE(type), dnum);
		return 1;
	}

	if ((*part = jffs2_part_info(*dev, pnum)) == NULL) {
		printf("no such partition\n");
		*dev = NULL;
		return 1;
	}

	*part_num = pnum;

	return 0;
}

/**
 * Find and delete partition. For partition id format see find_dev_and_part().
 *
 * @param id string describing device and partition
 * @return 0 on success, 1 otherwise
 */
static int delete_partition(const char *id)
{
	u8 pnum;
	struct mtd_device *dev;
	struct part_info *part;

	if (find_dev_and_part(id, &dev, &pnum, &part) == 0) {

		DEBUGF("delete_partition: device = %s%d, partition %d = (%s) 0x%08lx@0x%08lx\n",
				MTD_DEV_TYPE(dev->id->type), dev->id->num, pnum,
				part->name, part->size, part->offset);

		if (part_del(dev, part) != 0)
			return 1;

		if (generate_mtdparts_save(last_parts, MTDPARTS_MAXLEN) != 0) {
			printf("generated mtdparts too long, reseting to null\n");
			return 1;
		}
		return 0;
	}

	printf("partition %s not found\n", id);
	return 1;
}

/**
 * Accept character string describing mtd partitions and call device_parse()
 * for each entry. Add created devices to the global devices list.
 *
 * @param mtdparts string specifing mtd partitions
 * @return 0 on success, 1 otherwise
 */
static int parse_mtdparts(const char *const mtdparts)
{
	const char *p = mtdparts;
	struct mtd_device *dev;
	int err = 1;

	DEBUGF("\n---parse_mtdparts---\nmtdparts = %s\n\n", p);

	/* delete all devices and partitions */
	if (devices_init() != 0) {
		printf("could not initialise device list\n");
		return err;
	}

	/* re-read 'mtdparts' variable, devices_init may be updating env */
	p = getenv("mtdparts");

	if (strncmp(p, "mtdparts=", 9) != 0) {
		printf("mtdparts variable doesn't start with 'mtdparts='\n");
		return err;
	}
	p += 9;

	while (p && (*p != '\0')) {
		err = 1;
		if ((device_parse(p, &p, &dev) != 0) || (!dev))
			break;

		DEBUGF("+ device: %s\t%d\t%s\n", MTD_DEV_TYPE(dev->id->type),
				dev->id->num, dev->id->mtd_id);

		/* check if parsed device is already on the list */
		if (device_find(dev->id->type, dev->id->num) != NULL) {
			printf("device %s%d redefined, please correct mtdparts variable\n",
					MTD_DEV_TYPE(dev->id->type), dev->id->num);
			break;
		}

		list_add_tail(&dev->link, &devices);
		err = 0;
	}
	if (err == 1) {
		device_delall(&devices);
		return 1;
	}

	return 0;
}

/**
 * Parse provided string describing mtdids mapping (see file header for mtdids
 * variable format). Allocate memory for each entry and add all found entries
 * to the global mtdids list.
 *
 * @param ids mapping string
 * @return 0 on success, 1 otherwise
 */
static int parse_mtdids(const char *const ids)
{
	const char *p = ids;
	const char *mtd_id;
	int mtd_id_len;
	struct mtdids *id;
	struct list_head *entry, *n;
	struct mtdids *id_tmp;
	u8 type, num;
	u32 size;
	int ret = 1;

	DEBUGF("\n---parse_mtdids---\nmtdids = %s\n\n", ids);

	/* clean global mtdids list */
	list_for_each_safe(entry, n, &mtdids) {
		id_tmp = list_entry(entry, struct mtdids, link);
		DEBUGF("mtdids del: %d %d\n", id_tmp->type, id_tmp->num);
		list_del(entry);
		free(id_tmp);
	}
	last_ids[0] = '\0';
	INIT_LIST_HEAD(&mtdids);

	while(p && (*p != '\0')) {

		ret = 1;
		/* parse 'nor'|'nand'<dev-num> */
		if (id_parse(p, &p, &type, &num) != 0)
			break;

		if (*p != '=') {
			printf("mtdids: incorrect <dev-num>\n");
			break;
		}
		p++;

		/* check if requested device exists */
		if (device_validate(type, num, &size) != 0)
			return 1;

		/* locate <mtd-id> */
		mtd_id = p;
		if ((p = strchr(mtd_id, ',')) != NULL) {
			mtd_id_len = p - mtd_id + 1;
			p++;
		} else {
			mtd_id_len = strlen(mtd_id) + 1;
		}
		if (mtd_id_len == 0) {
			printf("mtdids: no <mtd-id> identifier\n");
			break;
		}

		/* check if this id is already on the list */
		int double_entry = 0;
		list_for_each(entry, &mtdids) {
			id_tmp = list_entry(entry, struct mtdids, link);
			if ((id_tmp->type == type) && (id_tmp->num == num)) {
				double_entry = 1;
				break;
			}
		}
		if (double_entry) {
			printf("device id %s%d redefined, please correct mtdids variable\n",
					MTD_DEV_TYPE(type), num);
			break;
		}

		/* allocate mtdids structure */
		if (!(id = (struct mtdids *)malloc(sizeof(struct mtdids) + mtd_id_len))) {
			printf("out of memory\n");
			break;
		}
		memset(id, 0, sizeof(struct mtdids) + mtd_id_len);
		id->num = num;
		id->type = type;
		id->size = size;
		id->mtd_id = (char *)(id + 1);
		strncpy(id->mtd_id, mtd_id, mtd_id_len - 1);
		id->mtd_id[mtd_id_len - 1] = '\0';
		INIT_LIST_HEAD(&id->link);

		DEBUGF("+ id %s%d\t%16d bytes\t%s\n",
				MTD_DEV_TYPE(id->type), id->num,
				id->size, id->mtd_id);

		list_add_tail(&id->link, &mtdids);
		ret = 0;
	}
	if (ret == 1) {
		/* clean mtdids list and free allocated memory */
		list_for_each_safe(entry, n, &mtdids) {
			id_tmp = list_entry(entry, struct mtdids, link);
			list_del(entry);
			free(id_tmp);
		}
		return 1;
	}

	return 0;
}

/**
 * Parse and initialize global mtdids mapping and create global
 * device/partition list.
 *
 * @return 0 on success, 1 otherwise
 */
int mtdparts_init(void)
{
	static int initialized = 0;
	const char *ids, *parts;
	const char *current_partition;
	int ids_changed;
	char tmp_ep[PARTITION_MAXLEN];

	DEBUGF("\n---mtdparts_init---\n");
	if (!initialized) {
		INIT_LIST_HEAD(&mtdids);
		INIT_LIST_HEAD(&devices);
		memset(last_ids, 0, MTDIDS_MAXLEN);
		memset(last_parts, 0, MTDPARTS_MAXLEN);
		memset(last_partition, 0, PARTITION_MAXLEN);
		initialized = 1;
	}

	/* get variables */
	ids = getenv("mtdids");
	parts = getenv("mtdparts");
	current_partition = getenv("partition");

	/* save it for later parsing, cannot rely on current partition pointer
	 * as 'partition' variable may be updated during init */
	tmp_ep[0] = '\0';
	if (current_partition)
		strncpy(tmp_ep, current_partition, PARTITION_MAXLEN);

	DEBUGF("last_ids  : %s\n", last_ids);
	DEBUGF("env_ids   : %s\n", ids);
	DEBUGF("last_parts: %s\n", last_parts);
	DEBUGF("env_parts : %s\n\n", parts);

	DEBUGF("last_partition : %s\n", last_partition);
	DEBUGF("env_partition  : %s\n", current_partition);

	/* if mtdids varible is empty try to use defaults */
	if (!ids) {
		if (mtdids_default) {
			DEBUGF("mtdids variable not defined, using default\n");
			ids = mtdids_default;
			setenv("mtdids", (char *)ids);
		} else {
			printf("mtdids not defined, no default present\n");
			return 1;
		}
	}
	if (strlen(ids) > MTDIDS_MAXLEN - 1) {
		printf("mtdids too long (> %d)\n", MTDIDS_MAXLEN);
		return 1;
	}

	/* do no try to use defaults when mtdparts variable is not defined,
	 * just check the length */
	if (!parts)
		printf("mtdparts variable not set, see 'help mtdparts'\n");

	if (parts && (strlen(parts) > MTDPARTS_MAXLEN - 1)) {
		printf("mtdparts too long (> %d)\n", MTDPARTS_MAXLEN);
		return 1;
	}

	/* check if we have already parsed those mtdids */
	if ((last_ids[0] != '\0') && (strcmp(last_ids, ids) == 0)) {
		ids_changed = 0;
	} else {
		ids_changed = 1;

		if (parse_mtdids(ids) != 0) {
			devices_init();
			return 1;
		}

		/* ok it's good, save new ids */
		strncpy(last_ids, ids, MTDIDS_MAXLEN);
	}

	/* parse partitions if either mtdparts or mtdids were updated */
	if (parts && ((last_parts[0] == '\0') || ((strcmp(last_parts, parts) != 0)) || ids_changed)) {
		if (parse_mtdparts(parts) != 0)
			return 1;

		if (list_empty(&devices)) {
			printf("mtdparts_init: no valid partitions\n");
			return 1;
		}

		/* ok it's good, save new parts */
		strncpy(last_parts, parts, MTDPARTS_MAXLEN);

		/* reset first partition from first dev from the list as current */
		current_dev = list_entry(devices.next, struct mtd_device, link);
		current_partnum = 0;
		current_save();

		DEBUGF("mtdparts_init: current_dev  = %s%d, current_partnum = %d\n",
				MTD_DEV_TYPE(current_dev->id->type),
				current_dev->id->num, current_partnum);
	}

	/* mtdparts variable was reset to NULL, delete all devices/partitions */
	if (!parts && (last_parts[0] != '\0'))
		return devices_init();

	/* do not process current partition if mtdparts variable is null */
	if (!parts)
		return 0;

	/* is current partition set in environment? if so, use it */
	if ((tmp_ep[0] != '\0') && (strcmp(tmp_ep, last_partition) != 0)) {
		struct part_info *p;
		struct mtd_device *cdev;
		u8 pnum;

		DEBUGF("--- getting current partition: %s\n", tmp_ep);

		if (find_dev_and_part(tmp_ep, &cdev, &pnum, &p) == 0) {
			current_dev = cdev;
			current_partnum = pnum;
			current_save();
		}
	} else if (getenv("partition") == NULL) {
		DEBUGF("no partition variable set, setting...\n");
		current_save();
	}

	return 0;
}
#else /* #ifdef CONFIG_JFFS2_CMDLINE */
/*
 * 'Static' version of command line mtdparts_init() routine. Single partition on
 * a single device configuration.
 */

/**
 * Parse and initialize global mtdids mapping and create global
 * device/partition list.
 *
 * @return 0 on success, 1 otherwise
 */
int mtdparts_init(void)
{
	static int initialized = 0;
	u32 size;
	char *dev_name;

	DEBUGF("\n---mtdparts_init---\n");
	if (!initialized) {
		struct mtdids *id;
		struct part_info *part;

		initialized = 1;
		current_dev = (struct mtd_device *)
			malloc(sizeof(struct mtd_device) +
					sizeof(struct part_info) +
					sizeof(struct mtdids));
		if (!current_dev) {
			printf("out of memory\n");
			return 1;
		}
		memset(current_dev, 0, sizeof(struct mtd_device) +
					sizeof(struct part_info) + sizeof(struct mtdids));

		id = (struct mtdids *)(current_dev + 1);
		part = (struct part_info *)(id + 1);

		/* id */
		id->mtd_id = "single part";

#if defined(CONFIG_JFFS2_DEV)
		dev_name = CONFIG_JFFS2_DEV;
#else
		dev_name = "nor0";
#endif

		if ((id_parse(dev_name, NULL, &id->type, &id->num) != 0) ||
				(device_validate(id->type, id->num, &size) != 0)) {
			printf("incorrect device: %s%d\n", MTD_DEV_TYPE(id->type), id->num);
			free(current_dev);
			return 1;
		}
		id->size = size;
		INIT_LIST_HEAD(&id->link);

		DEBUGF("dev id: type = %d, num = %d, size = 0x%08lx, mtd_id = %s\n",
				id->type, id->num, id->size, id->mtd_id);

		/* partition */
		part->name = "static";
		part->auto_name = 0;

#if defined(CONFIG_JFFS2_PART_SIZE)
		part->size = CONFIG_JFFS2_PART_SIZE;
#else
		part->size = SIZE_REMAINING;
#endif

#if defined(CONFIG_JFFS2_PART_OFFSET)
		part->offset = CONFIG_JFFS2_PART_OFFSET;
#else
		part->offset = 0x00000000;
#endif

		part->dev = current_dev;
		INIT_LIST_HEAD(&part->link);

		/* recalculate size if needed */
		if (part->size == SIZE_REMAINING)
			part->size = id->size - part->offset;

		DEBUGF("part  : name = %s, size = 0x%08lx, offset = 0x%08lx\n",
				part->name, part->size, part->offset);

		/* device */
		current_dev->id = id;
		INIT_LIST_HEAD(&current_dev->link);
		current_dev->num_parts = 1;
		INIT_LIST_HEAD(&current_dev->parts);
		list_add(&part->link, &current_dev->parts);
	}

	return 0;
}
#endif /* #ifdef CONFIG_JFFS2_CMDLINE */

/**
 * Return pointer to the partition of a requested number from a requested
 * device.
 *
 * @param dev device that is to be searched for a partition
 * @param part_num requested partition number
 * @return pointer to the part_info, NULL otherwise
 */
static struct part_info* jffs2_part_info(struct mtd_device *dev, unsigned int part_num)
{
	struct list_head *entry;
	struct part_info *part;
	int num;

	if (!dev)
		return NULL;

	DEBUGF("\n--- jffs2_part_info: partition number %d for device %s%d (%s)\n",
			part_num, MTD_DEV_TYPE(dev->id->type),
			dev->id->num, dev->id->mtd_id);

	if (part_num >= dev->num_parts) {
		printf("invalid partition number %d for device %s%d (%s)\n",
				part_num, MTD_DEV_TYPE(dev->id->type),
				dev->id->num, dev->id->mtd_id);
		return NULL;
	}

	/* locate partition number, return it */
	num = 0;
	list_for_each(entry, &dev->parts) {
		part = list_entry(entry, struct part_info, link);

		if (part_num == num++) {
			return part;
		}
	}

	return NULL;
}

/***************************************************/
/* U-boot commands				   */
/***************************************************/

/**
 * Routine implementing fsload u-boot command. This routine tries to load
 * a requested file from jffs2/cramfs filesystem on a current partition.
 *
 * @param cmdtp command internal data
 * @param flag command flag
 * @param argc number of arguments supplied to the command
 * @param argv arguments list
 * @return 0 on success, 1 otherwise
 */
int do_jffs2_fsload(cmd_tbl_t *cmdtp, int flag, int argc, char *argv[])
{
	char *fsname;
	char *filename;
	int size;
	struct part_info *part;
	ulong offset = load_addr;

	/* pre-set Boot file name */
	if ((filename = getenv("bootfile")) == NULL) {
		filename = "uImage";
	}

	if (argc == 2) {
		filename = argv[1];
	}
	if (argc == 3) {
		offset = simple_strtoul(argv[1], NULL, 16);
		load_addr = offset;
		filename = argv[2];
	}

	/* make sure we are in sync with env variables */
	if (mtdparts_init() !=0)
		return 1;

	if ((part = jffs2_part_info(current_dev, current_partnum))){

		/* check partition type for cramfs */
		fsname = (cramfs_check(part) ? "CRAMFS" : "JFFS2");
		printf("### %s loading '%s' to 0x%lx\n", fsname, filename, offset);

		if (cramfs_check(part)) {
			size = cramfs_load ((char *) offset, part, filename);
		} else {
			/* if this is not cramfs assume jffs2 */
			size = jffs2_1pass_load((char *)offset, part, filename);
		}

		if (size > 0) {
			char buf[10];
			printf("### %s load complete: %d bytes loaded to 0x%lx\n",
				fsname, size, offset);
			sprintf(buf, "%x", size);
			setenv("filesize", buf);
		} else {
			printf("### %s LOAD ERROR<%x> for %s!\n", fsname, size, filename);
		}

		return !(size > 0);
	}
	return 1;
}

/**
 * Routine implementing u-boot ls command which lists content of a given
 * directory on a current partition.
 *
 * @param cmdtp command internal data
 * @param flag command flag
 * @param argc number of arguments supplied to the command
 * @param argv arguments list
 * @return 0 on success, 1 otherwise
 */
int do_jffs2_ls(cmd_tbl_t *cmdtp, int flag, int argc, char *argv[])
{
	char *filename = "/";
	int ret;
	struct part_info *part;

	if (argc == 2)
		filename = argv[1];

	/* make sure we are in sync with env variables */
	if (mtdparts_init() !=0)
		return 1;

	if ((part = jffs2_part_info(current_dev, current_partnum))){

		/* check partition type for cramfs */
		if (cramfs_check(part)) {
			ret = cramfs_ls (part, filename);
		} else {
			/* if this is not cramfs assume jffs2 */
			ret = jffs2_1pass_ls(part, filename);
		}

		return ret ? 0 : 1;
	}
	return 1;
}

/**
 * Routine implementing u-boot fsinfo command. This routine prints out
 * miscellaneous filesystem informations/statistics.
 *
 * @param cmdtp command internal data
 * @param flag command flag
 * @param argc number of arguments supplied to the command
 * @param argv arguments list
 * @return 0 on success, 1 otherwise
 */
int do_jffs2_fsinfo(cmd_tbl_t *cmdtp, int flag, int argc, char *argv[])
{
	struct part_info *part;
	char *fsname;
	int ret;

	/* make sure we are in sync with env variables */
	if (mtdparts_init() !=0)
		return 1;

	if ((part = jffs2_part_info(current_dev, current_partnum))){

		/* check partition type for cramfs */
		fsname = (cramfs_check(part) ? "CRAMFS" : "JFFS2");
		printf("### filesystem type is %s\n", fsname);

		if (cramfs_check(part)) {
			ret = cramfs_info (part);
		} else {
			/* if this is not cramfs assume jffs2 */
			ret = jffs2_1pass_info(part);
		}

		return ret ? 0 : 1;
	}
	return 1;
}

/* command line only */
#ifdef CONFIG_JFFS2_CMDLINE
/**
 * Routine implementing u-boot chpart command. Sets new current partition based
 * on the user supplied partition id. For partition id format see find_dev_and_part().
 *
 * @param cmdtp command internal data
 * @param flag command flag
 * @param argc number of arguments supplied to the command
 * @param argv arguments list
 * @return 0 on success, 1 otherwise
 */
int do_jffs2_chpart(cmd_tbl_t *cmdtp, int flag, int argc, char *argv[])
{
/* command line only */
	struct mtd_device *dev;
	struct part_info *part;
	u8 pnum;

	if (mtdparts_init() !=0)
		return 1;

	if (argc < 2) {
		printf("no partition id specified\n");
		return 1;
	}

	if (find_dev_and_part(argv[1], &dev, &pnum, &part) != 0)
		return 1;

	current_dev = dev;
	current_partnum = pnum;
	current_save();

	printf("partition changed to %s%d,%d\n",
			MTD_DEV_TYPE(dev->id->type), dev->id->num, pnum);

	return 0;
}

/**
 * Routine implementing u-boot mtdparts command. Initialize/update default global
 * partition list and process user partition request (list, add, del).
 *
 * @param cmdtp command internal data
 * @param flag command flag
 * @param argc number of arguments supplied to the command
 * @param argv arguments list
 * @return 0 on success, 1 otherwise
 */
int do_jffs2_mtdparts(cmd_tbl_t *cmdtp, int flag, int argc, char *argv[])
{

	if (argc == 2) {
		if (strcmp(argv[1], "default") == 0) {
			setenv("mtdids", (char *)mtdids_default);
			setenv("mtdparts", (char *)mtdparts_default);
			setenv("partition", NULL);

			mtdparts_init();
			return 0;
		} else if (strcmp(argv[1], "delall") == 0) {
			/* this may be the first run, initialize lists if needed */
			mtdparts_init();

			setenv("mtdparts", NULL);

			/* devices_init() calls current_save() */
			return devices_init();
		}
	}

	/* make sure we are in sync with env variables */
	if (mtdparts_init() != 0)
		return 1;

	if (argc == 1) {
		list_partitions();
		return 0;
	}

	/* mtdparts add <mtd-dev> <size>[@<offset>] <name> [ro] */
	if (((argc == 5) || (argc == 6)) && (strcmp(argv[1], "add") == 0)) {
#define PART_ADD_DESC_MAXLEN 64
		char tmpbuf[PART_ADD_DESC_MAXLEN];
		u8 type, num, len;
		struct mtd_device *dev;
		struct mtd_device *dev_tmp;
		struct mtdids *id;
		struct part_info *p;

		if (id_parse(argv[2], NULL, &type, &num) != 0)
			return 1;

		if ((id = id_find(type, num)) == NULL) {
			printf("no such device %s defined in mtdids variable\n", argv[2]);
			return 1;
		}

		len = strlen(id->mtd_id) + 1;	/* 'mtd_id:' */
		len += strlen(argv[3]);		/* size@offset */
		len += strlen(argv[4]) + 2;	/* '(' name ')' */
		if (argv[5] && (strlen(argv[5]) == 2))
			len += 2;		/* 'ro' */

		if (len >= PART_ADD_DESC_MAXLEN) {
			printf("too long partition description\n");
			return 1;
		}
		sprintf(tmpbuf, "%s:%s(%s)%s",
				id->mtd_id, argv[3], argv[4], argv[5] ? argv[5] : "");
		DEBUGF("add tmpbuf: %s\n", tmpbuf);

		if ((device_parse(tmpbuf, NULL, &dev) != 0) || (!dev))
			return 1;

		DEBUGF("+ %s\t%d\t%s\n", MTD_DEV_TYPE(dev->id->type),
				dev->id->num, dev->id->mtd_id);

		if ((dev_tmp = device_find(dev->id->type, dev->id->num)) == NULL) {
			device_add(dev);
		} else {
			/* merge new partition with existing ones*/
			p = list_entry(dev->parts.next, struct part_info, link);
			if (part_add(dev_tmp, p) != 0) {
				device_del(dev);
				return 1;
			}
		}

		if (generate_mtdparts_save(last_parts, MTDPARTS_MAXLEN) != 0) {
			printf("generated mtdparts too long, reseting to null\n");
			return 1;
		}

		return 0;
	}

	/* mtdparts del part-id */
	if ((argc == 3) && (strcmp(argv[1], "del") == 0)) {
		DEBUGF("del: part-id = %s\n", argv[2]);

		return delete_partition(argv[2]);
	}

	printf ("Usage:\n%s\n", cmdtp->usage);
	return 1;
}
#endif /* #ifdef CONFIG_JFFS2_CMDLINE */

/***************************************************/
U_BOOT_CMD(
	fsload,	3,	0,	do_jffs2_fsload,
	"fsload\t- load binary file from a filesystem image\n",
	"[ off ] [ filename ]\n"
	"    - load binary file from flash bank\n"
	"      with offset 'off'\n"
);
U_BOOT_CMD(
	ls,	2,	1,	do_jffs2_ls,
	"ls\t- list files in a directory (default /)\n",
	"[ directory ]\n"
	"    - list files in a directory.\n"
);

U_BOOT_CMD(
	fsinfo,	1,	1,	do_jffs2_fsinfo,
	"fsinfo\t- print information about filesystems\n",
	"    - print information about filesystems\n"
);

#ifdef CONFIG_JFFS2_CMDLINE
U_BOOT_CMD(
	chpart,	2,	0,	do_jffs2_chpart,
	"chpart\t- change active partition\n",
	"part-id\n"
	"    - change active partition (e.g. part-id = nand0,1)\n"
);

U_BOOT_CMD(
	mtdparts,	6,	0,	do_jffs2_mtdparts,
	"mtdparts- define flash/nand partitions\n",
	"\n"
	"    - list partition table\n"
	"mtdparts delall\n"
	"    - delete all partitions\n"
	"mtdparts del part-id\n"
	"    - delete partition (e.g. part-id = nand0,1)\n"
	"mtdparts add <mtd-dev> <size>[@<offset>] [<name>] [ro]\n"
	"    - add partition\n"
	"mtdparts default\n"
	"    - reset partition table to defaults\n\n"
	"-----\n\n"
	"this command uses three environment variables:\n\n"
	"'partition' - keeps current partition identifier\n\n"
	"partition  := <part-id>\n"
	"<part-id>  := <dev-id>,part_num\n\n"
	"'mtdids' - linux kernel mtd device id <-> u-boot device id mapping\n\n"
	"mtdids=<idmap>[,<idmap>,...]\n\n"
	"<idmap>    := <dev-id>=<mtd-id>\n"
	"<dev-id>   := 'nand'|'nor'<dev-num>\n"
	"<dev-num>  := mtd device number, 0...\n"
	"<mtd-id>   := unique device tag used by linux kernel to find mtd device (mtd->name)\n\n"
	"'mtdparts' - partition list\n\n"
	"mtdparts=mtdparts=<mtd-def>[;<mtd-def>...]\n\n"
	"<mtd-def>  := <mtd-id>:<part-def>[,<part-def>...]\n"
	"<mtd-id>   := unique device tag used by linux kernel to find mtd device (mtd->name)\n"
	"<part-def> := <size>[@<offset>][<name>][<ro-flag>]\n"
	"<size>     := standard linux memsize OR '-' to denote all remaining space\n"
	"<offset>   := partition start offset within the device\n"
	"<name>     := '(' NAME ')'\n"
	"<ro-flag>  := when set to 'ro' makes partition read-only (not used, passed to kernel)\n"
);
#endif /* #ifdef CONFIG_JFFS2_CMDLINE */

/***************************************************/

#endif /* CFG_CMD_JFFS2 */


text:
package com.dytech.edge.admin.script.model;

public class OpTerm extends Node {
  protected Operator operator;
  protected Term term;

  public OpTerm(Operator operator, Term term) {
    this.operator = operator;
    this.term = term;
  }

  public Term getTerm() {
    return term;
  }

  public Operator getOperator() {
    return operator;
  }

  public void setOperator(Operator operator) {
    this.operator = operator;
  }

  public void setTerm(Term term) {
    this.term = term;
  }
}


text:
namespace paddle {
namespace operators {

struct InputsVisitor {
  template <typename OpType>
  const framework::VariableNameMap *operator()(const OpType *op) const {
    return &(op->Inputs());
  }
};

struct OutputsVisitor {
  template <typename OpType>
  const framework::VariableNameMap *operator()(const OpType *op) const {
    return &(op->Outputs());
  }
};

struct AttributeMapVisitor {
  const framework::AttributeMap *operator()(const framework::OpDesc *op) const {
    return &(op->GetAttrMap());
  }

  const framework::AttributeMap *operator()(
      const framework::OperatorBase *op) const {
    return &(op->Attrs());
  }
};

struct RawPointerVisitor {
  template <typename OpType>
  const void *operator()(const OpType *op) const {
    return op;
  }
};

const framework::VariableNameMap &OpVariant::Inputs() const {
  return *paddle::visit(InputsVisitor(), op_);
}

const framework::VariableNameMap &OpVariant::Outputs() const {
  return *paddle::visit(OutputsVisitor(), op_);
}

const framework::AttributeMap &OpVariant::Attrs() const {
  return *paddle::visit(AttributeMapVisitor(), op_);
}

const void *OpVariant::RawPointer() const {
  return paddle::visit(RawPointerVisitor(), op_);
}

void AppendOpVariantByOpName(const std::vector<framework::OpDesc *> &op_descs,
                             const std::string &candidate_op_name,
                             std::vector<OpVariant> *result_ops) {
  PADDLE_ENFORCE_NOT_NULL(
      result_ops,
      platform::errors::Unavailable("result_ops should not be a null_ptr."));
  for (auto *op_desc : op_descs) {
    PADDLE_ENFORCE_NOT_NULL(
        op_desc,
        platform::errors::Unavailable("op_desc should not be a null_ptr."));
    if (op_desc->Type() == candidate_op_name) {
      result_ops->emplace_back(op_desc);
    }
  }
}

void AppendOpVariantByOpName(
    const std::vector<framework::OpDesc *> &op_descs,
    const std::string &candidate_op_name,
    std::unordered_set<OpVariant, OpVariant::Hasher> *result_ops) {
  PADDLE_ENFORCE_NOT_NULL(
      result_ops,
      platform::errors::Unavailable("result_ops should not be a null_ptr."));
  for (auto *op_desc : op_descs) {
    PADDLE_ENFORCE_NOT_NULL(
        op_desc,
        platform::errors::Unavailable("op_desc should not be a null_ptr."));
    if (op_desc->Type() == candidate_op_name) {
      result_ops->emplace(op_desc);
    }
  }
}

}  // namespace operators
}  // namespace paddle


text:
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Sydowia 8: 195 (1954)

#### Original name
Didymosphaeria gaubae Petr., 1954

### Remarks
null


text:
<!DOCTYPE html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

  <title>
    Shannon - WI+RE

  </title>

  <meta name="description" content="">

    <meta name="DC.title" content="Shannon" />

    <meta name="DC.source" content="WI+RE - Quick and practical research and writing tutorials, collaboratively designed by students at UCLA." />

                <meta name="DC.creator" content="The WI+RE Team" />

        <meta name="DCterms.issued" content="June 05, 2020" />

        <meta name="DC.Type" content="team-member" />

        <meta name="DC.rights" content="Creative Commons Attribution-NonCommercial-ShareAlike" />

  <link href='https://fonts.googleapis.com/css?family=Lora:400,700,400italic,700italic' rel='stylesheet' type='text/css'>
  <link href='https://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800' rel='stylesheet' type='text/css'>

    <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.6.3/css/all.css" integrity="sha384-UHRtZLI+pbxtHCWp1t77Bi1L4ZtiqrqD80Kn4Z8NTSRyMA2Fd33n5dQ8lWUE00s/" crossorigin="anonymous">

    <link rel="stylesheet" href="/research-tips/assets/vendor/bootstrap/css/bootstrap.min.css">

  <link rel="stylesheet" href="/research-tips/assets/main.css">

    <link rel="stylesheet" href="/research-tips/assets/custom.css">

  <link rel="canonical" href="http://localhost:4000/about/creative-team/shannon/">
  <link rel="alternate" type="application/rss+xml" title="WI+RE" href="/research-tips/feed.xml">

    WI+RE
    <button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarResponsive" aria-controls="navbarResponsive" aria-expanded="false" aria-label="Toggle navigation">
      Menu

    </button>

          Home

          About

          Workshops

          Tutorials

          Handouts

          Contact

               Search

                        Shannon Roux

                Shannon worked with the WI+RE Team for two years, right as the project was getting started. Through WI+RE she was able to explore and build a variety of new skills like html coding on the WI+RE website, video editing on projects such as "Reading Strategies," and simple animation like in "Expanding Perspectives." Most of all Shannon took away a passion for the collaborative design process and for instructional design. Shannon is currently using and building this passion as a 3-4th grade special education teacher in Chicago.

Featured Projects:

                                <li data-target="#carouselExampleCaptions" data-slide-to="1"

Research Paper Planner

This research paper planner is designed to help students create and follow manageable deadlines for assignments, while also offering a means to track progress and persona health.

Integrating Citations

This visual and interactive tutorial offers a number of different ways for students to cite and integrate sources into their writing.

                          Previous

                          Next

My WI+RE Portfolio

Workshops

Getting Started with Research at UCLA

Developing Research Questions and Creating Keywords 5-star editor review on merlot.org

Finding Sources with the UCLA Library

Collecting and Citing Sources

Tutorials

Research Paper Planner

Find and Use Review Articles

Get Started with Zotero

Getting Started with Research at UCLA Winner of the ARLies award for Best Reflection of Diversity at the 2018 ARL Film Festival

Creating Literature Reviews

Expanding Perspectives in Your Search 5-star editor review on merlot.org

Integrating Citations

Finding Scholarly Articles 5-star editor review on merlot.org

Writing for Your Discipline

Turn Questions into Keywords

Reading Strategies

Communicating with Instructors: Email and Office Hours

Handouts

Integrating Citations

Contacting Instructors

Reading for Writing

Research Paper Planner

Find and Use Review Articles

Turn Questions Into Keywords

Sandbox Posts

Navigating the Undergradate Research Portal - Video Series

Design Jam #1!

WI+RE's favorite quotes!

My Contributions

I also contributed to:
                    Writing a Literature Review Accepted to the PRIMO database of Peer reviewed materials online Featured as a PRIMO site of the month 5-star editor review on merlot.org |
                    Research Abstracts |

                    ← Salma

                The WI+RE Team

                    Taylor →

            All content on this site is Creative Commons Attribution-NonCommercial-ShareAlike by  The WI+RE Team 2020

The WI+RE team is grateful for the ongoing support of UCLA Library.


text:
"""
WebDAV XML utilities.

This module provides XML utilities for use with WebDAV.

See RFC 2518: http://www.ietf.org/rfc/rfc2518.txt (WebDAV)
"""

__all__ = [
    "PrintXML",
    "encodeXMLName",
    "decodeXMLName",
]

try:
    import xml.dom.ext as ext
except ImportError:
    import twisted.web2.dav.element.xmlext as ext

def PrintXML(document, stream):
    document.normalize()
    ext.Print(document, stream)
    # For debugging, this is easier to read: (FIXME: disable for normal use)
    #ext.PrettyPrint(document, stream)

def encodeXMLName(name):
    """
    Encodes an XML (namespace, localname) pair into an ASCII string.
    If namespace is None, returns localname encoded as UTF-8.
    Otherwise, returns {namespace}localname encoded as UTF-8.
    """
    namespace, name = name
    if namespace is None: return name.encode("utf-8")
    return (u"{%s}%s" % (namespace, name)).encode("utf-8")

def decodeXMLName(name):
    """
    Decodes an XML (namespace, localname) pair from an ASCII string as encoded
    by encodeXMLName().
    """
    if name[0] is not "{": return (None, name.decode("utf-8"))

    index = name.find("}")

    if (index is -1 or not len(name) > index):
        raise ValueError("Invalid encoded name: %r" % (name,))

    return (name[1:index].decode("utf-8"), name[index+1:].decode("utf-8"))


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

<title>LocationHandler</title>
<meta name="date" content="2017-12-04">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

com.cmput301.t05.habilect

Class LocationHandler

java.lang.Object

com.cmput301.t05.habilect.LocationHandler

All Implemented Interfaces:

android.support.v4.app.ActivityCompat.OnRequestPermissionsResultCallback

public class LocationHandler
extends java.lang.Object
implements android.support.v4.app.ActivityCompat.OnRequestPermissionsResultCallback

This handles the location of the user if you need to retrieve it
 Created by Oliver on 10/11/2017.

Method Summary

All Methods Instance Methods Concrete Methods

Modifier and Type
Method and Description

android.location.Location
getLocation()

void
onRequestPermissionsResult(int requestCode,
                          java.lang.String[] permissions,
                          int[] grantResults)

Callback received when a permissions request has been completed.

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Method Detail

getLocation

public android.location.Location getLocation()

onRequestPermissionsResult

public void onRequestPermissionsResult(int requestCode,
                                       @NonNull
                                       java.lang.String[] permissions,
                                       @NonNull
                                       int[] grantResults)

Callback received when a permissions request has been completed.

Specified by:

onRequestPermissionsResult in interface android.support.v4.app.ActivityCompat.OnRequestPermissionsResultCallback

Skip navigation links

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


text:
namespace genetic
{
	using std::bind;
	using namespace std::placeholders;

	//Mutagens encapsulate a ternary function that takes a parent allele, a rng, and a prob and return random mutant Alleles
	//Implementations should use prob p to scale up the "strength" of the mutation, with 0 being no mutation and 1 being maximum.
	struct Mutagen
	{
		Allele (*mutate)(Allele, rng&, prob) = nullptr;
		Allele operator()(Allele a, rng &g, prob p) { return mutate(a, g, p); }
		vector<Allele> operator()(Allele a, rng &g, prob p, unsigned n) { return vector<Allele>(n, mutate(a, g, p)); }
		Mutagen(Allele (*F)(Allele, rng&, prob)) : mutate(F) {}
	};

	template <typename... Args>
	Mutagen makeMutagen(Allele (*F)(Allele, rng, prob, Args...), Args... args)
	{
		return Mutagen(bind(F, _1, _2, _3, args...));
	};

	namespace mutagenFuncs
	{
		Allele FlipRandom (Allele a, rng &g, prob p);
		Allele CopyRandom (Allele a, rng &g, prob p);
		Allele DeleteRandomSite (Allele a, rng &g, unsigned n);
		Allele FlipNearSite (Allele a, rng &g, unsigned n, unsigned site, prob stddev);
		Allele ReversePortion (Allele a, rng &g, unsigned n, unsigned site1, unsigned site2, prob stddev);
		Allele CopyPortion (Allele a, rng &g, unsigned n, unsigned site1, unsigned site2, prob stddev);
		Allele FlipAllSites (Allele a, rng &g, prob p);
		Allele LeftBitshift (Allele a, rng &g, prob p);
		Allele LeftBitshiftCyclic (Allele a, rng &g, prob p);
		Allele RightBitshiftAllele (Allele a, rng &g, prob p);
		Allele RightBitshiftCyclicAllele (Allele a, rng &g, prob p);
	}

	namespace mutagens
	{
		using namespace mutagenFuncs;
		static Mutagen FlipRandomSites (&FlipRandom);
		static Mutagen CopyRandomSites (&CopyRandom);
	}
}

#endif


text:
namespace chromecast {
namespace shell {

// When enabled, these bindings can be used to open a message channel with the
// Assistant. These bindings are only enabled for a small set of first-party
// apps.
class AssistantBindings : public CastBinding,
                          public chromecast::mojom::AssistantMessageClient {
 public:
  AssistantBindings(content::RenderFrame* frame,
                    const base::Value& feature_config);
  ~AssistantBindings() override;
  AssistantBindings(const AssistantBindings&) = delete;
  AssistantBindings& operator=(const AssistantBindings&) = delete;

 private:
  friend class ::chromecast::CastBinding;

  // chromecast::mojom::AssistantMessageClient implementation:
  void OnMessage(base::Value message) override;

  // CastBinding implementation:
  void Install(v8::Local<v8::Object> cast_platform,
               v8::Isolate* isolate) override;

  // Binding methods
  void SetAssistantMessageHandler(
      v8::Local<v8::Function> assistant_message_handler);
  void SendAssistantRequest(const std::string& request);

  void ReconnectMessagePipe();
  void OnAssistantConnectionError();

  void FlushV8ToAssistantQueue();

  const mojo::Remote<chromecast::mojom::AssistantMessageService>&
  GetMojoInterface();

  base::RepeatingTimer reconnect_assistant_timer_;
  mojo::Remote<chromecast::mojom::AssistantMessageService> assistant_;
  base::Value feature_config_;

  mojo::Receiver<chromecast::mojom::AssistantMessageClient>
      message_client_binding_;
  mojo::Remote<chromecast::mojom::AssistantMessagePipe> message_pipe_;
  std::vector<std::string> v8_to_assistant_queue_;

  v8::UniquePersistent<v8::Function> assistant_message_handler_;

  base::WeakPtr<AssistantBindings> weak_this_;
  base::WeakPtrFactory<AssistantBindings> weak_factory_;
};

}  // namespace shell
}  // namespace chromecast

#endif  // CHROMECAST_RENDERER_ASSISTANT_BINDINGS_H_


text:
import os
os.chdir('bindings/python')
execfile('setup.py')


text:
'use strict';
// This file is auto-generated using scripts/doc-sync.js

  /**
   * Timeline record contains information about the recorded activity.
   *
   * @param {string} type Event type.
   * @param {Object} data Event data.
   * @param {number} startTime Start time.
   * @param {number=} endTime End time.
   * @param {Array.<TimelineEvent>=} children Nested records.
   * @param {string=} thread If present, identifies the thread that produced the event.
   * @param {Console.StackTrace=} stackTrace Stack trace.
   * @param {string=} frameId Unique identifier of the frame within the page that the event relates to.
   */
exports.TimelineEvent =
function TimelineEvent(props) {
  this.type = props.type;
  this.data = props.data;
  this.startTime = props.startTime;
  this.endTime = props.endTime;
  this.children = props.children;
  this.thread = props.thread;
  this.stackTrace = props.stackTrace;
  this.frameId = props.frameId;
};