text:
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE78_OS_Command_Injection__wchar_t_environment_system_41.c
Label Definition File: CWE78_OS_Command_Injection.one_string.label.xml
Template File: sources-sink-41.tmpl.c
*/
/*
 * @description
 * CWE: 78 OS Command Injection
 * BadSource: environment Read input from an environment variable
 * GoodSource: Fixed string
 * Sink: system
 *    BadSink : Execute command in data using system()
 * Flow Variant: 41 Data flow: data passed as an argument from one function to another in the same source file
 *
 * */

#include "std_testcase.h"

#include <wchar.h>

#ifdef _WIN32
#define FULL_COMMAND L"dir "
#else
#include <unistd.h>
#define FULL_COMMAND L"ls "
#endif

#define ENV_VARIABLE L"ADD"

#ifdef _WIN32
#define GETENV _wgetenv
#else
#define GETENV getenv
#endif

#ifdef _WIN32
#define SYSTEM _wsystem
#else /* NOT _WIN32 */
#define SYSTEM system
#endif

#ifndef OMITBAD

void CWE78_OS_Command_Injection__wchar_t_environment_system_41_badSink(wchar_t * data)
{
    /* POTENTIAL FLAW: Execute command in data possibly leading to command injection */
    if (SYSTEM(data) != 0)
    {
        printLine("command execution failed!");
        exit(1);
    }
}

void CWE78_OS_Command_Injection__wchar_t_environment_system_41_bad()
{
    wchar_t * data;
    wchar_t data_buf[100] = FULL_COMMAND;
    data = data_buf;
    {
        /* Append input from an environment variable to data */
        size_t dataLen = wcslen(data);
        wchar_t * environment = GETENV(ENV_VARIABLE);
        /* If there is data in the environment variable */
        if (environment != NULL)
        {
            /* POTENTIAL FLAW: Read data from an environment variable */
            wcsncat(data+dataLen, environment, 100-dataLen-1);
        }
    }
    CWE78_OS_Command_Injection__wchar_t_environment_system_41_badSink(data);
}

#endif /* OMITBAD */

#ifndef OMITGOOD

void CWE78_OS_Command_Injection__wchar_t_environment_system_41_goodG2BSink(wchar_t * data)
{
    /* POTENTIAL FLAW: Execute command in data possibly leading to command injection */
    if (SYSTEM(data) != 0)
    {
        printLine("command execution failed!");
        exit(1);
    }
}

/* goodG2B uses the GoodSource with the BadSink */
static void goodG2B()
{
    wchar_t * data;
    wchar_t data_buf[100] = FULL_COMMAND;
    data = data_buf;
    /* FIX: Append a fixed string to data (not user / external input) */
    wcscat(data, L"*.*");
    CWE78_OS_Command_Injection__wchar_t_environment_system_41_goodG2BSink(data);
}

void CWE78_OS_Command_Injection__wchar_t_environment_system_41_good()
{
    goodG2B();
}

#endif /* OMITGOOD */

/* 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

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

#endif

redpajama_set_name: RedPajamaGithub


text:
#define KATE_INTERNAL
#include "kate_internal.h"

#ifdef HAVE_STDLIB_H
#include <stdlib.h>
#endif
#ifdef HAVE_STRING_H
#include <string.h>
#endif
#include "kate/kate.h"
#include "kate_decode_state.h"
#include "kate_encode_state.h"

#define MKVER1(x) #x
#define MKVER2(x,y) MKVER1(x) "." MKVER1(y)
#define MKVER3(x,y,z) MKVER1(x)"."MKVER1(y)"."MKVER1(z)

/**
  \ingroup version
  Returns the version number of this version of libkate, in 8.8.8 major.minor.patch format
  \returns the version number of libkate
  */
int kate_get_version(void)
{
  return (KATE_VERSION_MAJOR<<16)|(KATE_VERSION_MINOR<<8)|KATE_VERSION_PATCH;
}

/**
  \ingroup version
  Returns a human readable string representing the version number of this version of libkate
  \returns the version number of libkate as a string
  */
const char *kate_get_version_string(void)
{
  return "libkate " MKVER3(KATE_VERSION_MAJOR,KATE_VERSION_MINOR,KATE_VERSION_PATCH) " (Tiger)";
}

/**
  \ingroup version
  Returns the highest bitstream version number that this version of libkate supports, in 8.8 major.minor format
  \returns the bitstream version number
  */
int kate_get_bitstream_version(void)
{
  return (KATE_BITSTREAM_VERSION_MAJOR<<8)|(KATE_BITSTREAM_VERSION_MINOR);
}

/**
  \ingroup version
  Returns a string representing the highest bitstream version number that this version of libkate supports
  \returns the bitstream version number as a string
  */
const char *kate_get_bitstream_version_string(void)
{
  return "kate bitstream " MKVER2(KATE_BITSTREAM_VERSION_MAJOR,KATE_BITSTREAM_VERSION_MINOR);
}

/**
  Destroys a kate_state structure.
  The kate_state structure should have been initialized with kate_decode_init or kate_encode_init.
  \param k the kate_state structure to clear
  \returns 0 success
  \returns KATE_E_* error
 */
int kate_clear(kate_state *k)
{
  if (!k) return KATE_E_INVALID_PARAMETER;

  if (k->kds) {
    kate_decode_state_destroy(k->kds);
    k->kds=NULL;
  }
  if (k->kes) {
    kate_encode_state_destroy(k->kes);
    k->kes=NULL;
  }

  return 0;
}

static inline int kate_ascii_tolower(int c) __attribute__((const));
static inline int kate_ascii_tolower(int c)
{
  if (c>='A' && c<='Z') return c|32;
  return c;
}

int kate_ascii_strncasecmp(const char *s0,const char *s1,size_t n)
{
  while (n--) {
    int c0=kate_ascii_tolower(*s0++);
    int c1=kate_ascii_tolower(*s1++);
    if (c0!=c1) return c0-c1;
    if (!c0) return 0;
  }
  return 0;
}

int kate_ascii_strcasecmp(const char *s0,const char *s1)
{
  return kate_ascii_strncasecmp(s0,s1,(size_t)-1);
}

/**
  \ingroup misc
  Initializes a kate region to sensible defaults
  \param kr the region to initialize
  \returns 0 success
  \returns KATE_E_* error
  */
int kate_region_init(kate_region *kr)
{
  static const kate_region default_region={
    kate_percentage,
    10,80,80,10,
    -1,
    0,
    0,
    NULL,
    {0,0,0,0,0}
  };

  if (!kr) return KATE_E_INVALID_PARAMETER;
  memcpy(kr,&default_region,sizeof(kate_region));
  return 0;
}

/**
  \ingroup misc
  Initializes a kate style to sensible defaults
  \param ks the style to initialize
  \returns 0 success
  \returns KATE_E_* error
  */
int kate_style_init(kate_style *ks)
{
  static const kate_style default_style={
    0,0,
    {255,255,255,255},
    {0,0,0,0},
    {255,255,255,255},
    kate_pixel,
    -1,-1,
    kate_pixel,
    0,0,0,0,
    0,
    0,
    0,
    0,
    0,
    kate_wrap_word,
    0,
    NULL,
    NULL,
    {0,0,0,0,0,0,0,0}
  };

  if (!ks) return KATE_E_INVALID_PARAMETER;
  memcpy(ks,&default_style,sizeof(kate_style));
  return 0;
}

/**
  \ingroup misc
  Initializes a kate palette to sensible defaults
  \param kp the palette to initialize
  \returns 0 success
  \returns KATE_E_* error
  */
int kate_palette_init(kate_palette *kp)
{
  static const kate_palette default_palette={
    0,
    NULL,
    NULL,
    {0}
  };

  if (!kp) return KATE_E_INVALID_PARAMETER;
  memcpy(kp,&default_palette,sizeof(kate_palette));
  return 0;
}

/**
  \ingroup misc
  Initializes a kate bitmap to sensible defaults. Obsolete, use kate_bitmap_init_new in new code.
  \param kb the bitmap to initialize
  \returns 0 success
  \returns KATE_E_* error
  */
int kate_bitmap_init(kate_bitmap *kb)
{
  typedef struct kate_bitmap_old_equivalent {
    size_t width;                                  /**< width in pixels */
    size_t height;                                 /**< height in pixels */
    unsigned char bpp;                             /**< bits per pixel, from 1 to 8, or 0 for a raw PNG bitmap */
    kate_bitmap_type type;                         /**< the type of this bitmap */
    unsigned char pad0[1];
    unsigned char internal;
    int palette;                                   /**< index of the default palette to use */
    unsigned char *pixels;                         /**< pixels, rows first, one byte per pixel regardless of bpp */
    size_t size;                                   /**< for raw bitmaps, number of bytes in pixels */
    int x_offset;                                  /**< the horizontal offset to the logical origin of the bitmap */
    int y_offset;                                  /**< the vertical offset to the logical origin of the bitmap */
  } kate_bitmap_old_equivalent;
  static const kate_bitmap_old_equivalent default_bitmap={
    0,0,
    0,
    kate_bitmap_type_png,
    {0},
    0, /* internal flag - meta and later not initialized */
    -1,
    NULL,
    0,
    0,0,
  };

  if (!kb) return KATE_E_INVALID_PARAMETER;
  memcpy(kb,&default_bitmap,sizeof(kate_bitmap_old_equivalent));
  return 0;
}

/**
  \ingroup misc
  Initializes a kate bitmap to sensible defaults
  \param kb the bitmap to initialize
  \returns 0 success
  \returns KATE_E_* error
  */
int kate_bitmap_init_new(kate_bitmap *kb)
{
  static const kate_bitmap default_bitmap={
    0,0,
    0,
    kate_bitmap_type_png,
    {0},
    1, /* internal flag - all initialized */
    -1,
    NULL,
    0,
    0,0,
    NULL,
    {0,0,0,0,0,0,0,0,0,0,0,0,0,0}
  };

  if (!kb) return KATE_E_INVALID_PARAMETER;
  memcpy(kb,&default_bitmap,sizeof(kate_bitmap));
  return 0;
}

/**
  \ingroup misc
  Initializes a kate curve to sensible defaults
  \param kc the curve to initialize
  \returns 0 success
  \returns KATE_E_* error
  */
int kate_curve_init(kate_curve *kc)
{
  static const kate_curve default_curve={
    kate_curve_none,
    0,
    NULL,
    {0,0,0,0,0}
  };

  if (!kc) return KATE_E_INVALID_PARAMETER;
  memcpy(kc,&default_curve,sizeof(kate_curve));
  return 0;
}

/**
  \ingroup misc
  Initializes a kate motion to sensible defaults
  \param km the motion to initialize
  \returns 0 success
  \returns KATE_E_* error
  */
int kate_motion_init(kate_motion *km)
{
  static const kate_motion default_motion={
    0,
    NULL,
    NULL,
    kate_motion_mapping_none,
    kate_motion_mapping_none,
    kate_motion_semantics_time,
    0,
    0,
    NULL,
    {0,0,0,0}
  };

  if (!km) return KATE_E_INVALID_PARAMETER;
  memcpy(km,&default_motion,sizeof(kate_motion));
  return 0;
}

void *kate_checked_malloc(size_t n,size_t sz)
{
  size_t mul;
  if (kate_check_mul_overflow(n,sz,&mul)) return NULL;
  return kate_malloc(mul);
}

void *kate_checked_realloc(void *ptr,size_t n,size_t sz)
{
  size_t mul;
  if (kate_check_mul_overflow(n,sz,&mul)) return NULL;
  return kate_realloc(ptr,mul);
}


text:
package mods.belgabor.amtweaker.mods.vanilla.commands;

import com.google.common.base.Joiner;
import mods.belgabor.amtweaker.AMTweaker;
import mods.belgabor.amtweaker.util.CommandLoggerBase;
import net.minecraft.block.Block;
import net.minecraft.command.CommandBase;
import net.minecraft.command.ICommandSender;
import net.minecraft.item.*;
import net.minecraft.util.ChatComponentText;
import net.minecraft.util.ChunkCoordinates;
import net.minecraft.world.World;
import net.minecraft.world.chunk.Chunk;
import net.minecraftforge.oredict.OreDictionary;

import java.io.*;
import java.util.*;

/**
 * Created by Belgabor on 03.06.2016.
 */
public class VanillaCommandBlockstats extends CommandBase {
    @Override
    public String getCommandName() {
        return "blockstats";
    }

    @Override
    public String getCommandUsage(ICommandSender sender) {
        return "/blockstats [range] - Dump block statistics around player in a certain range";
    }

    private static class BlockStats {
        public final Block block;
        public final int meta;
        public int count = 0;
        public int minLevel = Integer.MAX_VALUE;
        public int maxLevel = 0;

        private BlockStats(Block block, int meta) {
            this.block = block;
            this.meta = meta;
        }

        protected void minmax(int y) {
            minLevel = Math.min(minLevel, y);
            maxLevel = Math.max(maxLevel, y);
        }

        protected String getTag() {
            try {
                return CommandLoggerBase.getObjectDeclaration(new ItemStack(block, 1, meta));
            } catch (NullPointerException e) {
                return block.getUnlocalizedName() + "#" + meta;
            }
        }

        protected String getName() {
            try {
                return (new ItemStack(block, 1, meta)).getDisplayName();
            } catch (NullPointerException e) {
                return block.getLocalizedName();
            }
        }

        protected String getOres() {
            try {
                int[] ids = OreDictionary.getOreIDs(new ItemStack(block, 1, meta));
                if (ids.length ==0)
                    return "";
                ArrayList<String> ores = new ArrayList<>();
                for (int id : ids) {
                    ores.add(OreDictionary.getOreName(id));
                }
                return Joiner.on(", ").join(ores);
            } catch (NullPointerException e) {
                return "";
            }
        }
    }

    private static class BlockStatsComp implements Comparator<BlockStats> {

        @Override
        public int compare(BlockStats o1, BlockStats o2) {
            return o1.count - o2.count;
        }
    }

    @Override
    public void processCommand(ICommandSender sender, String[] arguments) {
        if (arguments.length != 1) {
            getCommandSenderAsPlayer(sender).addChatComponentMessage(new ChatComponentText("Wrong number of parameters."));
            return;
        }
        int range;
        try {
            range = Integer.parseInt(arguments[0]);
        } catch (NumberFormatException e) {
            range = -1;
        }
        if (range <= 0) {
            getCommandSenderAsPlayer(sender).addChatComponentMessage(new ChatComponentText("Range must be a positive number."));
            return;
        }
        getCommandSenderAsPlayer(sender).addChatComponentMessage(new ChatComponentText("Starting to collect block statistics, radius " + range));
        World world = sender.getEntityWorld();
        ChunkCoordinates center = sender.getPlayerCoordinates();
        ChunkCoordinates from = new ChunkCoordinates(center.posX - range, 0, center.posZ - range);
        ChunkCoordinates to = new ChunkCoordinates(center.posX + range, world.getActualHeight() - 1, center.posZ + range);

        Map<String, BlockStats> stats = new HashMap<>();
        int total = 0;

        for (int x = from.posX; x <= to.posX; x++) {
            for (int z = from.posZ; z <= to.posZ; z++) {
                Chunk chunk = world.getChunkFromBlockCoords(x, z);
                int chunkX = x & 15;
                int chunkZ = z & 15;
                for (int y = from.posY; y <= to.posY; y++) {
                    Block block = chunk.getBlock(chunkX, y, chunkZ);
                    int meta = chunk.getBlockMetadata(chunkX, y, chunkZ);
                    String tag = block.getUnlocalizedName() + "#" + meta;

                    BlockStats s = stats.get(tag);
                    if (s == null) {
                        s = new BlockStats(block, meta);
                        stats.put(tag, s);
                    }

                    s.count++;
                    total++;
                    s.minmax(y);
                }
            }
        }

        TreeSet<BlockStats> sorted = new TreeSet<>(new BlockStatsComp());
        sorted.addAll(stats.values());
        OutputStreamWriter writer = null;
        boolean errors = false;
        try {
            writer = new OutputStreamWriter(new FileOutputStream(new File(AMTweaker.logsDir, String.format("blockstats_%d_%d_%d_%d.csv", world.provider.dimensionId, center.posX, center.posZ, range))), "utf-8");
            writer.write("Block;Unlocalized Name;Name;Meta;OreDict;count;total;Min Level;Max Level;Dimension ID;Dimension Name\n");
        } catch (IOException e) {
            getCommandSenderAsPlayer(sender).addChatComponentMessage(new ChatComponentText("Warning: Unable to open log file."));
        }
        for (BlockStats bl : sorted) {
            getCommandSenderAsPlayer(sender).addChatComponentMessage(new ChatComponentText(String.format("%s  %d  %d-%d", bl.getTag(), bl.count, bl.minLevel, bl.maxLevel)));
            if (writer != null) {
                try {
                    writer.write(String.format("%s;%s;\"%s\";%d;%s;%d;%d;%d;%d;%d;\"%s\"\n",
                            bl.getTag(), bl.block.getUnlocalizedName(), bl.getName(), bl.meta, bl.getOres(), bl.count, total, bl.minLevel, bl.maxLevel, world.provider.dimensionId, world.provider.getDimensionName()));
                    writer.flush();
                } catch (IOException e) {
                    errors = true;
                }
            }
        }
        getCommandSenderAsPlayer(sender).addChatComponentMessage(new ChatComponentText("Total: " + total));
        if (errors)
            getCommandSenderAsPlayer(sender).addChatComponentMessage(new ChatComponentText("There were errors writing the log file, it may be incomplete."));
    }
}


text:
package yoda;

import ninja.Context;
import ninja.Filter;
import ninja.FilterChain;
import ninja.Result;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import yoda.threads.ResponderExecutionHandler;

import com.google.inject.Inject;
import com.google.inject.Singleton;

@Singleton
public class Async implements Filter {

    private static final Logger logger = LoggerFactory.getLogger(Async.class);

    private final ResponderExecutionHandler responderExecutionHandler;

    @Inject
    public Async(ResponderExecutionHandler responderExecutionHandler) {

        // This throws a runtime exception if not correct properties
        this.responderExecutionHandler = responderExecutionHandler;

        logger.info(this.responderExecutionHandler.toString());

    }

    @Override
    public Result filter(FilterChain filterChain, Context context) {
        // Its all Async...
        responderExecutionHandler.execute(context, filterChain);
        return null;
    }

}


text:
package com.twu.biblioteca;

/**
 * Created by Administrator on 2015/5/31.
 */

        import java.awt.Button;

        import java.awt.Color;

        import java.awt.Frame;

        import java.awt.Label;

        import java.awt.Panel;

        import java.awt.TextField;

public class demo {

    public static void main(String agrs[]){

        Frame nw= new Frame("Login");

        Panel nn=new Panel();

        Label a1=new Label("Name   ");

        Label a2=new Label("Password ");

        TextField b1=new TextField("name     ");

        TextField b2=new TextField("password");

        Button n1=new Button("Login");

        nn.add(a1);

        nn.add(b1);

        nn.add(a2);

        nn.add(b2);

        nn.add(n1);

        nw.add(nn);

        nw.setBackground(Color.white);

        nw.setSize(300, 300);

        nw.setVisible(true);

    }

}


text:
@implementation OcrCaptureSession

@synthesize captureSession = _captureSession;
@synthesize previewLayer = _previewLayer;
@synthesize stillImageOutput = _stillImageOutput;
@synthesize stillImage = _stillImage;

- (id)init
{
	if ((self = [super init]))
    {
		[self setCaptureSession:[[AVCaptureSession alloc] init]];
	}
	return self;
}

- (void)addVideoPreviewLayer
{
	[self setPreviewLayer:[[AVCaptureVideoPreviewLayer alloc] initWithSession:[self captureSession]]];
	[_previewLayer setVideoGravity:AVLayerVideoGravityResizeAspectFill];

}

- (void)addVideoInputFromCamera
{
    AVCaptureDevice *backCamera;

    NSArray *devices = [AVCaptureDevice devices];

    for (AVCaptureDevice *device in devices)
    {
        if ([device hasMediaType:AVMediaTypeVideo])
        {
            if ([device position] == AVCaptureDevicePositionBack)
            {
                backCamera = device;
                [self toggleFlash];
            }
        }
    }

    NSError *error = nil;

    AVCaptureDeviceInput *backFacingCameraDeviceInput = [AVCaptureDeviceInput deviceInputWithDevice:backCamera error:&error];

    if (!error)
    {
        if ([_captureSession canAddInput:backFacingCameraDeviceInput])
        {
            [_captureSession addInput:backFacingCameraDeviceInput];
        }
    }
}

- (void)setFlashOn:(BOOL)boolWantsFlash
{
    flashOn = boolWantsFlash;
    [self toggleFlash];
}

- (void)toggleFlash
{
    NSArray *devices = [AVCaptureDevice devices];

    for (AVCaptureDevice *device in devices)
    {
        if (device.flashAvailable) {
            if (flashOn)
            {
                [device lockForConfiguration:nil];
                device.flashMode = AVCaptureFlashModeOn;
                [device unlockForConfiguration];
            }
            else
            {
                [device lockForConfiguration:nil];
                device.flashMode = AVCaptureFlashModeOff;
                [device unlockForConfiguration];
            }
        }
    }
}

- (void)addStillImageOutput
{
    [self setStillImageOutput:[[AVCaptureStillImageOutput alloc] init]];
    NSDictionary *outputSettings = [[NSDictionary alloc] initWithObjectsAndKeys:AVVideoCodecJPEG,AVVideoCodecKey,nil];
    [[self stillImageOutput] setOutputSettings:outputSettings];

    AVCaptureConnection *videoConnection = nil;

    for (AVCaptureConnection *connection in [_stillImageOutput connections])
    {
        for (AVCaptureInputPort *port in [connection inputPorts])
        {
            if ([[port mediaType] isEqual:AVMediaTypeVideo] )
            {
                videoConnection = connection;
                break;
            }
        }
        if (videoConnection)
        {
            break;
        }
    }
    [_captureSession setSessionPreset:AVCaptureSessionPresetPhoto];
    [_captureSession addOutput:[self stillImageOutput]];
}

- (void)captureStillImage
{
	AVCaptureConnection *videoConnection = nil;
	for (AVCaptureConnection *connection in [[self stillImageOutput] connections])
    {
		for (AVCaptureInputPort *port in [connection inputPorts])
        {
			if ([[port mediaType] isEqual:AVMediaTypeVideo])
            {
				videoConnection = connection;
				break;
			}
		}

		if (videoConnection)
        {
            break;
        }
	}

	[_stillImageOutput captureStillImageAsynchronouslyFromConnection:videoConnection
                                                         completionHandler:
     ^(CMSampleBufferRef imageSampleBuffer, NSError *error) {

         if (imageSampleBuffer)
         {
             CFDictionaryRef exifAttachments = CMGetAttachment(imageSampleBuffer, kCGImagePropertyExifDictionary, NULL);
             if (exifAttachments)
             {
                 //NSLog(@"attachements: %@", exifAttachments);
             } else
             {
                 //NSLog(@"no attachments");
             }
             NSData *imageData = [AVCaptureStillImageOutput jpegStillImageNSDataRepresentation:imageSampleBuffer];
             UIImage *image = [[UIImage alloc] initWithData:imageData];
             [self setStillImage:image];

             [[NSNotificationCenter defaultCenter] postNotificationName:kImageCapturedSuccessfully object:nil];
         }
     }];
}

- (void)dealloc {

	[[self captureSession] stopRunning];

	_previewLayer = nil;
	_captureSession = nil;
    _stillImageOutput = nil;
    _stillImage = nil;
}

@end


text:
package com.facebook.drawee.drawable;

import android.graphics.Color;
import android.graphics.drawable.Drawable;

import org.robolectric.RobolectricTestRunner;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;

import static org.junit.Assert.*;
import static org.mockito.Mockito.*;

@RunWith(RobolectricTestRunner.class)
public class RoundedCornersDrawableTest {

  private Drawable mUnderlyingDrawable;
  private RoundedCornersDrawable mRoundedCornersDrawable;
  private Drawable.Callback mCallback;

  @Before
  public void setup() {
    mUnderlyingDrawable = mock(Drawable.class);
    mCallback = mock(Drawable.Callback.class);
    mRoundedCornersDrawable = new RoundedCornersDrawable(mUnderlyingDrawable);
    mRoundedCornersDrawable.setCallback(mCallback);
  }

  @Test
  public void testInitialSetup() {
    assertEquals(RoundedCornersDrawable.Type.OVERLAY_COLOR, mRoundedCornersDrawable.mType);
    assertFalse(mRoundedCornersDrawable.mIsCircle);
    assertArrayEquals(new float[]{0, 0, 0, 0, 0, 0, 0, 0}, mRoundedCornersDrawable.mRadii, 0);
    assertEquals(0, mRoundedCornersDrawable.mPaint.getColor());
  }

  @Test
  public void testSetType() {
    RoundedCornersDrawable.Type type = RoundedCornersDrawable.Type.CLIPPING;
    mRoundedCornersDrawable.setType(type);
    verify(mCallback).invalidateDrawable(mRoundedCornersDrawable);
    assertEquals(type, mRoundedCornersDrawable.mType);
  }

  @Test
  public void testSetCircle() {
    mRoundedCornersDrawable.setCircle(true);
    verify(mCallback).invalidateDrawable(mRoundedCornersDrawable);
    assertTrue(mRoundedCornersDrawable.mIsCircle);
  }

  @Test
  public void testSetRadii() {
    mRoundedCornersDrawable.setRadii(new float[]{1, 2, 3, 4, 5, 6, 7, 8});
    verify(mCallback).invalidateDrawable(mRoundedCornersDrawable);
    assertArrayEquals(new float[] {1, 2, 3, 4, 5, 6, 7, 8}, mRoundedCornersDrawable.mRadii, 0);
  }

  @Test
  public void testSetRadius() {
    mRoundedCornersDrawable.setRadius(9);
    verify(mCallback).invalidateDrawable(mRoundedCornersDrawable);
    assertArrayEquals(new float[]{9, 9, 9, 9, 9, 9, 9, 9}, mRoundedCornersDrawable.mRadii, 0);
  }

  @Test
  public void testSetOverlayColor() {
    int overlayColor = 0xC0123456;
    mRoundedCornersDrawable.setOverlayColor(overlayColor);
    verify(mCallback).invalidateDrawable(mRoundedCornersDrawable);
    assertEquals(overlayColor, mRoundedCornersDrawable.mOverlayColor);
  }

  @Test
  public void testSetBorder() {
    float borderWidth = 0.7f;
    int borderColor = Color.CYAN;
    mRoundedCornersDrawable.setBorder(borderColor, borderWidth);
    verify(mCallback).invalidateDrawable(mRoundedCornersDrawable);
    assertEquals(borderColor, mRoundedCornersDrawable.mBorderColor);
    assertEquals(borderWidth, mRoundedCornersDrawable.mBorderWidth, 0);
  }
}


text:
<?php

require_once __DIR__ . '/../../../vendor/autoload.php';
require_once __DIR__ . '/morse.php';

$outputFile = __DIR__ . '/output.php';

$outputFileContents = file_get_contents($outputFile);

if (preg_match('/\s+$/', $outputFileContents, $matches)) {
    $encodedMorse = substr($matches[0], 1);
    $originalMorse = str_replace(
        ["\n", "\t"],
        ['.', '-'],
        $encodedMorse
    );

    $morse = new Morse();
    $morse->synthesize($originalMorse);
    //$morse->synthesize($originalMorse, 'la', 'leeeeeeeeeeeeeee');
}


text:
//
//  PINRemoteImageBasicCache.h
//  Pods
//
//  Created by Aleksei Shevchenko on 7/28/16.
//
//

#import <Foundation/Foundation.h>
#import "PINRemoteImageCaching.h"

/**
 *  Simplistic <PINRemoteImageCacheProtocol> wrapper based on NSCache.
 *  not persisting any data on disk
 */
@interface PINRemoteImageBasicCache : NSObject <PINRemoteImageCaching>

@end


text:
<?php  echo $title; ?>

    <?php echo validation_errors(); ?>
    <?php echo form_open('verifylogin/index'); ?>

    Username:
    <input class=" input-lg " type="text" id="username" name="username" placeholder="Username" value="<?php echo set_value('username')?>"/>

    Password:
    <input type="password" class="input-lg"  id="password" placeholder="Password" name="password"/>

    <input class ="btn btn-primary col-md-offset-0 " type="submit" value="Login"/>
    <a class="btn btn-primary col-md-1.5" href="<?php echo base_url(); ?>verifylogin/register/">Not yes registered !
  </form>


text:
<?php

namespace WindowsAzure\Table\Models;

/**
 * Holds optional parameters for queryEntities API
 *
 * @category  Microsoft
 * @package   WindowsAzure\Table\Models
 * @author    Azure PHP SDK <azurephpsdk@microsoft.com>
 * @copyright 2012 Microsoft Corporation
 * @license   http://www.apache.org/licenses/LICENSE-2.0  Apache License 2.0
 * @version   Release: @package_version@
 * @link      https://github.com/windowsazure/azure-sdk-for-php
 */
class QueryEntitiesOptions extends TableServiceOptions
{
    /**
     * @var Query
     */
    private $_query;

    /**
     * @var string
     */
    private $_nextPartitionKey;

    /**
     * @var string
     */
    private $_nextRowKey;

    /**
     * Constructs new QueryEntitiesOptions object.
     */
    public function __construct()
    {
        $this->_query = new Query();
    }

    /**
     * Gets query.
     *
     * @return Query
     */
    public function getQuery()
    {
        return $this->_query;
    }

    /**
     * Sets query.
     *
     * You can either sets the whole query *or* use the individual query functions
     * like (setTop).
     *
     * @param string $query The query instance.
     *
     * @return none
     */
    public function setQuery($query)
    {
        $this->_query = $query;
    }

    /**
     * Gets entity next partition key.
     *
     * @return string
     */
    public function getNextPartitionKey()
    {
        return $this->_nextPartitionKey;
    }

    /**
     * Sets entity next partition key.
     *
     * @param string $nextPartitionKey The entity next partition key value.
     *
     * @return none
     */
    public function setNextPartitionKey($nextPartitionKey)
    {
        $this->_nextPartitionKey = $nextPartitionKey;
    }

    /**
     * Gets entity next row key.
     *
     * @return string
     */
    public function getNextRowKey()
    {
        return $this->_nextRowKey;
    }

    /**
     * Sets entity next row key.
     *
     * @param string $nextRowKey The entity next row key value.
     *
     * @return none
     */
    public function setNextRowKey($nextRowKey)
    {
        $this->_nextRowKey = $nextRowKey;
    }

    /**
     * Gets filter.
     *
     * @return Filters\Filter
     */
    public function getFilter()
    {
        return $this->_query->getFilter();
    }

    /**
     * Sets filter.
     *
     * You can either use this individual function or use setQuery to set the whole
     * query object.
     *
     * @param Filters\Filter $filter value.
     *
     * @return none.
     */
    public function setFilter($filter)
    {
        $this->_query->setFilter($filter);
    }

    /**
     * Gets top.
     *
     * @return integer.
     */
    public function getTop()
    {
        return $this->_query->getTop();
    }

    /**
     * Sets top.
     *
     * You can either use this individual function or use setQuery to set the whole
     * query object.
     *
     * @param integer $top value.
     *
     * @return none.
     */
    public function setTop($top)
    {
        $this->_query->setTop($top);
    }

    /**
     * Adds a field to select fields.
     *
     * You can either use this individual function or use setQuery to set the whole
     * query object.
     *
     * @param string $field The value of the field.
     *
     * @return none.
     */
    public function addSelectField($field)
    {
        $this->_query->addSelectField($field);
    }

    /**
     * Gets selectFields.
     *
     * @return array.
     */
    public function getSelectFields()
    {
        return $this->_query->getSelectFields();
    }

    /**
     * Sets selectFields.
     *
     * You can either use this individual function or use setQuery to set the whole
     * query object.
     *
     * @param array $selectFields value.
     *
     * @return none.
     */
    public function setSelectFields($selectFields)
    {
        $this->_query->setSelectFields($selectFields);
    }
}


text:
```bash
wget https://raw.github.com/kaustubh-karkare/todolist/master/todolist.py
alias todo='${PWD}/todolist.py'
todo --help # display documentation and usage examples
```

### Development

```bash
./src/__build.py ./todolist.py
```


text:
<!DOCTYPE html>

        <meta charset="UTF-8">
        <title>Tree</title>
        <link rel="stylesheet" type="text/css" href="./css/tui-example-style.css" />
        <link rel="stylesheet" type="text/css" href="./css/docs.css" />
        <link rel="stylesheet" type="text/css" href="../dist/tui-tree.css" />

            <button id="addChildBtn">add child</button>
            <button id="removeChildBtn">remove child</button>
            <button id="sortBtn">sort</button>


text:
package image;

import org.eclipse.swt.*;
import org.eclipse.swt.graphics.*;
import org.eclipse.swt.widgets.*;

public class Snippet194 {
	Display display;
	Color white, red, green, blue;
	PaletteData palette;
	Font font;

	public static void main(String[] args) {
		new Snippet194().run();
	}

	public void run() {
		display = new Display();
		RGB whiteRGB = new RGB(0xff, 0xff, 0xff);
		RGB redRGB = new RGB(0xff, 0, 0);
		RGB greenRGB = new RGB(0, 0xff, 0);
		RGB blueRGB = new RGB(0, 0, 0xff);
		palette = new PaletteData(new RGB[] {
				whiteRGB,	// 0
				redRGB,		// 1
				greenRGB,	// 2
				blueRGB });	// 3
		white = new Color(display, whiteRGB);
		red = new Color(display, redRGB);
		green = new Color(display, greenRGB);
		blue = new Color(display, blueRGB);
		font = new Font(display, "Comic Sans MS", 24, SWT.BOLD);

		ImageData[] data = new ImageData[4];
		data[0] = newFrame("",  white, false, 0, 0, 101, 55, SWT.DM_FILL_NONE, 40);
		data[1] = newFrame("S", red,   true,  0, 0,  30, 55, SWT.DM_FILL_NONE, 40);
		data[2] = newFrame("W", green, true, 28, 0,  39, 55, SWT.DM_FILL_NONE, 40);
		data[3] = newFrame("T", blue,  true, 69, 0,  32, 55, SWT.DM_FILL_BACKGROUND, 200);

		ImageLoader loader = new ImageLoader();
		loader.data = data;
		loader.backgroundPixel = 0;
		loader.logicalScreenHeight = data[0].height;
		loader.logicalScreenWidth = data[0].width;
		loader.repeatCount = 0; // run forever
		try {
			loader.save("swt.gif", SWT.IMAGE_GIF);
		} catch (SWTException ex) {
			System.out.println("Error saving GIF: " + ex);
		} finally {
			white.dispose();
			red.dispose();
			green.dispose();
			blue.dispose();
			font.dispose();
			display.dispose();
		}
	}

	ImageData newFrame(String letter, Color color, boolean transparent, int x, int y, int width, int height, int disposalMethod, int delayTime) {
		ImageData temp = new ImageData(width, height, 2, palette); // 4-color palette has depth 2
		Image image = new Image(display, temp);
		GC gc = new GC(image);
		gc.setBackground(white);
		gc.fillRectangle(0, 0, width, height);
		gc.setForeground(color);
		gc.setFont(font);
		gc.drawString(letter, 5, 5);
		gc.dispose();
		ImageData frame = image.getImageData();
		if (transparent) frame.transparentPixel = 0; // white
		image.dispose();
		frame.x = x;
		frame.y = y;
		frame.disposalMethod = disposalMethod;
		frame.delayTime = delayTime;
		return frame;
	}
}


text:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<widget>
	<access origin="https://minus.com/" subdomains="true"/>
	<access origin="http://minus.com/" subdomains="true"/>
	<access origin="http://dgbc7tshfzi70.cloudfront.net" subdomains="true"/>
</widget>


text:
import scrapy
import urlparse
from yellow.items import ContactItem, AddressItem
import yellow.settings

class ContactSpider(scrapy.Spider):
    name = "contacts"
    allowed_domains = ["seccionamarilla.com.mx"]
    def __init__(self, category='medicos', state=''):
        self.start_urls = []
        for state in yellow.settings.MX_STATES:
            self.start_urls.append('http://www.seccionamarilla.com.mx/resultados/%s/%s/1' % (category, state))

    def parse(self, response):
        for card in response.css('.vcard'):

            address = AddressItem()
            str_address = ''.join(card.css('.street-address::text').extract()).strip().split(',');
            for i in range(0, len(str_address)):
                if i == 0:
                    address['street'] = str_address[i].strip()
                elif i == 1:
                    address['neighborhood'] = str_address[i].strip()
                else:
                    address['municipality'] = str_address[i].strip()

            address['postal_code'] = ''.join(card.css('.postal-code::text').extract()).strip()
            address['state'] = ''.join(card.css('.locality').xpath('acronym/@title').extract())

            contact = ContactItem()
            contact['name'] = ''.join(card.css('.org').xpath('a/text()').extract()).strip()
            contact['phone'] = ''.join(card.css('.phone-number').xpath('span/text()').extract())
            contact['category'] = ''.join(card.css('.category::text').extract()).strip()
            contact['web_site'] = ''.join(card.css('.url::text').extract())
            contact['address'] = dict(address)

            contact['rating'] = ''.join(card.css('.rating').xpath('@class').extract()).replace('rating star', '')
            contact['votes'] = ''.join(card.css('.votes::text').extract())

            key = ''.join(card.xpath('.//a[contains(@id, "Name_Normal")]/@id').extract()).replace('Name_Normal-', '')
            if not key:
                key = ''.join(card.xpath('.//a[contains(@id, "Info_Normal")]/@id').extract()).replace('Info_Normal-', '')
            contact['key'] = key

            full_info = ''.join(card.xpath('.//a[contains(@id, "Info_Normal")]/@href').extract())
            if (len(full_info) > 0):
                request = scrapy.Request(full_info, callback=self.parse_full_contact)
                request.meta['contact'] = contact
                yield request
            else:
                yield contact

        btn_next = response.css('.icon.next')
        if not btn_next.extract():
            return

        url = urlparse.urljoin('http://www.seccionamarilla.com.mx', btn_next.xpath('@href').extract()[0])
        yield scrapy.Request(url, callback=self.parse)

    def parse_full_contact(self, response):
        contact = response.request.meta['contact']

        contact['email'] = ''.join(response.xpath('//a[contains(@href, "mailto")]/@href').extract()).replace('mailto:', '')
        contact['web_site'] = ''.join(response.css('.super_pagina').xpath('@href').extract())
        contact['payment_types'] = response.css('.pago').xpath('a/text()').extract()
        contact['services'] = response.css('.servicios').xpath('ul/li/text()').extract()
        contact['schedules'] = response.css('.horarios').xpath('p/text()').extract()

        position = ''.join(response.css('[name="geo.position"]').xpath('@content').extract()).split(';')
        region = ''.join(response.css('[name="geo.region"]').xpath('@content').extract())
        placename = ''.join(response.css('[name="geo.placename"]').xpath('@content').extract())

        if(len(position) == 2):
            contact['geolocation'] = {
                'placename': placename,
                'region': region,
                'position': {
                    'latitude': position[0],
                    'longitude': position[1]
                }
            }
        yield contact


text: See the presentation [here](https://jkissling.github.io/presentations/EU-DevSummit/2018/ts-js-api/)


text:
BOOST_AUTO_TEST_SUITE( vm )

BOOST_AUTO_TEST_SUITE( instruction_pointer )

struct instruction_pointer_fixture
{
  instruction_pointer_fixture() : pointer( segment ) {}
  perseus::detail::code_segment segment;
  perseus::detail::instruction_pointer pointer;
};

BOOST_FIXTURE_TEST_CASE( moving_test, instruction_pointer_fixture )
{
  BOOST_TEST_MESSAGE( "reading from and moving the instruction pointer" );
  using perseus::detail::instruction_pointer;
  segment.push< char >( 'a' );
  segment.push< char >( 'b' );
  segment.push< char >( 'c' );

  BOOST_CHECK_EQUAL( 0, static_cast< instruction_pointer::value_type >( pointer ) );
  BOOST_CHECK_EQUAL( 'a', pointer.read< char >() );
  BOOST_CHECK_EQUAL( 1, static_cast< instruction_pointer::value_type >( pointer ) );
  BOOST_CHECK_EQUAL( 'b', pointer.read< char >() );
  BOOST_CHECK_EQUAL( 2, static_cast< instruction_pointer::value_type >( pointer ) );
  BOOST_CHECK_EQUAL( 'c', pointer.read< char >() );
  BOOST_CHECK_EQUAL( 3, static_cast< instruction_pointer::value_type >( pointer ) );
  // check this with a copy so the original remains unchanged
  BOOST_CHECK_THROW( instruction_pointer( pointer ).read< char >(), perseus::code_segmentation_fault );
  BOOST_CHECK_EQUAL( 3, static_cast< instruction_pointer::value_type >( pointer ) );
  BOOST_REQUIRE_THROW( pointer += 1, perseus::code_segmentation_fault );
  BOOST_CHECK_EQUAL( 3, static_cast< instruction_pointer::value_type >( pointer ) );
  pointer += -3;
  BOOST_CHECK_EQUAL( 0, static_cast< instruction_pointer::value_type >( pointer ) );
  BOOST_CHECK_EQUAL( 'a', pointer.read< char >() );
  BOOST_CHECK_EQUAL( 1, static_cast< instruction_pointer::value_type >( pointer ) );
  BOOST_REQUIRE_THROW( pointer += -2, perseus::code_segmentation_fault );
  BOOST_CHECK_EQUAL( 1, static_cast< instruction_pointer::value_type >( pointer ) );
  pointer += 1;
  BOOST_CHECK_EQUAL( 2, static_cast< instruction_pointer::value_type >( pointer ) );
  BOOST_CHECK_EQUAL( 'c', pointer.read< char >() );
  BOOST_CHECK_EQUAL( 3, static_cast< instruction_pointer::value_type >( pointer ) );
}

BOOST_FIXTURE_TEST_CASE( singlebyte_encoding_test, instruction_pointer_fixture )
{
  BOOST_TEST_MESSAGE( "opcode encoding - single-byte opcode" );
  using perseus::detail::opcode;
  opcode code = static_cast< opcode >( 42 ); // something that fits into a single byte
  segment.push< opcode >( code );

  BOOST_CHECK_EQUAL( code, pointer.read< opcode >() );
  BOOST_CHECK_THROW( pointer.read< char >(), perseus::code_segmentation_fault );
}

BOOST_FIXTURE_TEST_CASE( multibyte_encoding_test, instruction_pointer_fixture )
{
  BOOST_TEST_MESSAGE( "opcode encoding - multi-byte opcode" );
  using perseus::detail::opcode;
  opcode code = static_cast< opcode >( 12345 ); // something that would not fit into a single byte
  segment.push< opcode >( code );
  segment.push< unsigned int >( 42 );

  BOOST_CHECK_EQUAL( code, pointer.read< opcode >() );
  BOOST_CHECK_EQUAL( 42u, pointer.read< unsigned int >() );
  BOOST_CHECK_THROW( pointer.read< char >(), perseus::code_segmentation_fault );
}

BOOST_AUTO_TEST_SUITE_END()

BOOST_AUTO_TEST_SUITE_END()


text:
<!DOCTYPE html>

Creating a Website

Our Enigneering class also learned how to create a website, which is how you are reading this now. We used sites like Github which gives you a platform for your coding. Finally, after we finished this coding in our file, we then were able to put our site on the web for everyone to see!


text:
Finora abbiamo visto come la GPU gestisce un gran numero di thread paralleli, ciascuno responsabile nell'assegnazione d'un colore ad una frazione dell'immagine totale. Sebbene ogni thread parallelo è cieco nei confronti degli altri, dobbiamo essere in grado d'inviare alcuni input dalla CPU a tutti i thread. A causa dell'architettura della scheda grafica tali input saranno uguali (*uniform*) per tutti i thread e necessariamente impostati come di *sola lettura*. In altre parole, ogni thread riceve gli stessi dati che possono essere letti ma non possono essere cambiati.

Questi input sono chiamati ```uniform``` e sono disponibili nella maggior parte di tipi supportati: ```float```, ```vec2```, ```vec3```, ```vec4```, ```mat2```, ```mat3```, ```mat4```, ```sampler2D``` e ```samplerCube```. Gli Uniforms sono definiti con i rispettivi tipi, all'inizio del codice, dopo aver definito la precisione della virgola mobile.

```glsl
#ifdef GL_ES
precision mediump float;
#endif

uniform vec2 u_resolution; // dimensione del Canvas (larghezza, altezza)
uniform vec2 u_mouse;      // posizione del mouse (x,y) in pixels
uniform float u_time;	  // tempo in secondi da quando lo shader è iniziato
```

È possibile immaginare gli uniforms come piccoli ponti tra la CPU e la GPU. I nomi variano da applicazione ad applicazione, ma in questa serie di esempi userò: ```u_time``` (tempo in secondi da quando lo shader è iniziato), ```u_resolution``` (la dimensione della finestra in cui lo shader è in corso d'elaborazione) e ```u_mouse``` (la posizione in pixel del mouse all'interno della finestra). Seguirò la convenzione di mettere ```u_``` prima del nome degli uniforms per essere espliciti sulla natura di questa variabile, ma incontrerete varie nomenclature per gli uniforms. Per esempio [ShaderToy.com](https://www.shadertoy.com/) utilizza gli stessi uniforms, ma con i seguenti nomi:

```glsl
uniform vec3 iResolution;   // dimensione del Canvas (in pixels)
uniform vec4 iMouse;        // posizione del mouse in pixels. xy: corrente, zw: click
uniform float iTime;        // tempo (in secondi) da quando lo shader è iniziato
```

Ma ora basta chiacchiere, vediamo gli uniforms in azione. Nel seguente codice utilizziamo ```u_time``` - il numero di secondi da quando lo shader è iniziato - insieme ad una funzione seno per animare con una transizione la quantità di rosso sullo schermo.

Come potete vedere GLSL ha molte sorprese. La GPU ha funzioni trigonometriche ed esponenziali, che sono accelerate dall'hardware. Alcune di queste funzioni sono: [```sin()```](../glossary/?search=sin), [```cos()```](../glossary/?search=cos), [```tan()```](../glossary/?search=tan), [```asin()```](../glossary/?search=asin), [```acos()```](../glossary/?search=acos), [```atan()```](../glossary/?search=atan), [```pow()```](../glossary/?search=pow), [```exp()```](../glossary/?search=exp), [```log()```](../glossary/?search=log), [```sqrt()```](../glossary/?search=sqrt), [```abs()```](../glossary/?search=abs), [```sign()```](../glossary/?search=sign), [```floor()```](../glossary/?search=floor), [```ceil()```](../glossary/?search=ceil), [```fract()```](../glossary/?search=fract), [```mod()```](../glossary/?search=mod), [```min()```](../glossary/?search=min), [```max()```](../glossary/?search=max) and [```clamp()```](../glossary/?search=clamp).

Ora è il momento di giocare con il codice qui sopra.

* Rallentate la frequenza fino a quando il cambiamento di colore diventa quasi impercettibile.

* Aumentate la frequenza fino a vedere un solo colore, senza sfarfallio.

* Date tre frequenze differenti ai tre canali (RGB) per ottenere motivi e comportamenti interessanti.

## gl_FragCoord

Allo stesso modo GLSL ci dà un output di default, ```vec4 gl_FragColor```, ma anche un input di default, ```vec4 gl_FragCoord```, che contiene le coordinate sullo schermo del *pixel* o del *screen fragment* del thread attivo. Con ```vec4 gl_FragCoord```, sappiamo dove un thread sta lavorando all'interno dello schermo. In questo caso la variabile non è un ```uniform``` perché sarà diversa da thread a thread. Le variabili che cambiano in ogni thread, come ```gl_FragCoord```, sono chiamate *varying*.

Nel codice qui sopra *normalizziamo* le coordinate del fragment dividendole per la risoluzione totale dello schermo. In questo modo i valori andranno tra ```0.0``` e ```1.0```, una tecnica che rende facile mappare i valori X e Y per i canali ROSSO e VERDE.

Nel mondo degli shaders non abbiamo troppe risorse per il debug a parte l'assegnazione di colori intensi alle variabili e cercare di trovargli un senso. Scoprirete che a volte programmando in GLSL è come mettere una nave all'interno di una bottiglia: un processo difficile, bello e gratificante.

![](08.png)

Ora è il momento di mettere in pratica gli insegnamenti che abbiamo imparato.

* Sapreste dire dove è la coordinata ```(0.0,0.0)``` sul nostro schermo?

* E dove sono ```(1.0,0.0)```, ```(0.0,1.0)```, ```(0.5,0.5)``` e ```(1.0,1.0)```?

* Riuscite ad immaginare come usare ```u_mouse``` sapendo che i valori sono espressi in pixel e NON in valori normalizzati? Sapresti usare ```u_mouse``` per muovere i colori?

* Sapreste trovare un modo interessante per cambiare questo pattern grafico utilizzando ```u_time``` e le coordinate ```u_mouse```?

Dopo aver fatto questi esercizi, ci si potrebbe chiedere dove si potrebbero provare i nuovi super poteri che gli shader ci hanno dato. Nel prossimo capitolo vedremo come creare i vostri shader in Three.js, Processing e openFrameworks.


text:
/* jshint esversion: 6 */

import React from "react";
import { default as swal } from "sweetalert2";

class Task extends React.Component {
  btnSettingsRef = React.createRef();
  liRef = React.createRef();
  inputRef = React.createRef();

  state = {
    taskId: this.props.task.taskId || 0,
    description: this.props.task.description || "<< Empty >>"
  };

  onMouseEnter = () => {
    this.btnSettingsRef.value.classList.add("scale-in");
  };

  onMouseLeave = () => {
    this.btnSettingsRef.value.classList.remove("scale-in");
  };

  onEdit = () => {
    swal({
      html: `

                            <textarea id="editTaskDescription" class="materialize-textarea" maxlength="120" data-length="120">${
                              this.state.description
                            }</textarea>
                            Task Description

`,
      showCancelButton: true,
      allowOutsideClick: false,
      confirmButtonText: `<i class="fa fa-save"></i>  Save`,
      confirmButtonClass: "waves-effect waves-light z-depth-4 btn green",
      cancelButtonText: `<i class="fa fa-close"></i>  Cancel`,
      cancelButtonClass: "waves-effect waves-light z-depth-4 btn red",
      buttonsStyling: false,
      preConfirm: () => {
        return new Promise((resolve, reject) => {
          const desc = document.getElementById("editTaskDescription");
          if (desc.value) {
            resolve(desc.value);
            this.setState({
              description: desc.value
            });
          } else {
            reject("You need to provide a task description.");
          }
        });
      },
      onOpen: () => {
        const descInput = document.getElementById("editTaskDescription");
        descInput.focus();
        // descInput.characterCounter();
      }
    }).then(
      result => {
        swal({
          type: "success",
          html: "The change has been saved."
        });
      },
      dismiss => {
        // dismiss can be 'cancel', 'overlay',
        // 'close', and 'timer'
        if (dismiss === "cancel") {
          swal("Cancelled", "No changes were made.", "error");
        }
      }
    );
  };

  onDelete = () => {
    this.liRef.value.classList.add("animated", "zoomOutLeft");
    setTimeout(() => {
      this.liRef.value.classList.remove("scale-in");
      this.props.removeTask(this.state.taskId);
    }, 600);
  };

  componentDidMount() {
    setTimeout(() => this.liRef.value.classList.add("scale-in"), 100);
  }

  render() {
    return (

         {this.state.description}

    );
  }
}

export default Task;


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Placolecanora muralis var. albocretacea B. de Lesd.

### Remarks
null


text:
import React, { MouseEvent, Key } from 'react';
import { Link, RouteComponentProps, withRouter } from 'react-router-dom';
import moment from 'moment';
import {
  Behavior,
  css,
  getChartMetadataRegistry,
  QueryFormData,
  styled,
  t,
} from '@superset-ui/core';
import { Menu } from 'src/components/Menu';
import { NoAnimationDropdown } from 'src/components/Dropdown';
import ShareMenuItems from 'src/dashboard/components/menu/ShareMenuItems';
import downloadAsImage from 'src/utils/downloadAsImage';
import { FeatureFlag, isFeatureEnabled } from 'src/featureFlags';
import CrossFilterScopingModal from 'src/dashboard/components/CrossFilterScopingModal/CrossFilterScopingModal';
import { getSliceHeaderTooltip } from 'src/dashboard/util/getSliceHeaderTooltip';
import { Tooltip } from 'src/components/Tooltip';
import Icons from 'src/components/Icons';
import ModalTrigger from 'src/components/ModalTrigger';
import Button from 'src/components/Button';
import ViewQueryModal from 'src/explore/components/controls/ViewQueryModal';
import { ResultsPaneOnDashboard } from 'src/explore/components/DataTablesPane';

const MENU_KEYS = {
  CROSS_FILTER_SCOPING: 'cross_filter_scoping',
  DOWNLOAD_AS_IMAGE: 'download_as_image',
  EXPLORE_CHART: 'explore_chart',
  EXPORT_CSV: 'export_csv',
  EXPORT_FULL_CSV: 'export_full_csv',
  FORCE_REFRESH: 'force_refresh',
  FULLSCREEN: 'fullscreen',
  TOGGLE_CHART_DESCRIPTION: 'toggle_chart_description',
  VIEW_QUERY: 'view_query',
  VIEW_RESULTS: 'view_results',
};

const VerticalDotsContainer = styled.div`
  padding: ${({ theme }) => theme.gridUnit / 4}px
    ${({ theme }) => theme.gridUnit * 1.5}px;

  .dot {
    display: block;
  }

  &:hover {
    cursor: pointer;
  }
`;

const RefreshTooltip = styled.div`
  height: auto;
  margin: ${({ theme }) => theme.gridUnit}px 0;
  color: ${({ theme }) => theme.colors.grayscale.base};
  line-height: 21px;
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  justify-content: flex-start;
`;

const getScreenshotNodeSelector = (chartId: string | number) =>
  `.dashboard-chart-id-${chartId}`;

const VerticalDotsTrigger = () => (
  <VerticalDotsContainer>

  </VerticalDotsContainer>
);

export interface SliceHeaderControlsProps {
  slice: {
    description: string;
    viz_type: string;
    slice_name: string;
    slice_id: number;
    slice_description: string;
    form_data?: { emit_filter?: boolean };
  };

  componentId: string;
  dashboardId: number;
  chartStatus: string;
  isCached: boolean[];
  cachedDttm: string[] | null;
  isExpanded?: boolean;
  updatedDttm: number | null;
  isFullSize?: boolean;
  isDescriptionExpanded?: boolean;
  formData: QueryFormData;
  exploreUrl: string;

  forceRefresh: (sliceId: number, dashboardId: number) => void;
  logExploreChart?: (sliceId: number) => void;
  toggleExpandSlice?: (sliceId: number) => void;
  exportCSV?: (sliceId: number) => void;
  exportFullCSV?: (sliceId: number) => void;
  handleToggleFullSize: () => void;

  addDangerToast: (message: string) => void;
  addSuccessToast: (message: string) => void;

  supersetCanExplore?: boolean;
  supersetCanShare?: boolean;
  supersetCanCSV?: boolean;
  sliceCanEdit?: boolean;
}
type SliceHeaderControlsPropsWithRouter = SliceHeaderControlsProps &
  RouteComponentProps;
interface State {
  showControls: boolean;
  showCrossFilterScopingModal: boolean;
}

const dropdownIconsStyles = css`
  &&.anticon > .anticon:first-child {
    margin-right: 0;
    vertical-align: 0;
  }
`;

class SliceHeaderControls extends React.PureComponent<
  SliceHeaderControlsPropsWithRouter,
  State
> {
  constructor(props: SliceHeaderControlsPropsWithRouter) {
    super(props);
    this.toggleControls = this.toggleControls.bind(this);
    this.refreshChart = this.refreshChart.bind(this);
    this.handleMenuClick = this.handleMenuClick.bind(this);

    this.state = {
      showControls: false,
      showCrossFilterScopingModal: false,
    };
  }

  refreshChart() {
    if (this.props.updatedDttm) {
      this.props.forceRefresh(
        this.props.slice.slice_id,
        this.props.dashboardId,
      );
    }
  }

  toggleControls() {
    this.setState(prevState => ({
      showControls: !prevState.showControls,
    }));
  }

  handleMenuClick({
    key,
    domEvent,
  }: {
    key: Key;
    domEvent: MouseEvent<HTMLElement>;
  }) {
    switch (key) {
      case MENU_KEYS.FORCE_REFRESH:
        this.refreshChart();
        this.props.addSuccessToast(t('Data refreshed'));
        break;
      case MENU_KEYS.CROSS_FILTER_SCOPING:
        this.setState({ showCrossFilterScopingModal: true });
        break;
      case MENU_KEYS.TOGGLE_CHART_DESCRIPTION:
        // eslint-disable-next-line no-unused-expressions
        this.props.toggleExpandSlice &&
          this.props.toggleExpandSlice(this.props.slice.slice_id);
        break;
      case MENU_KEYS.EXPLORE_CHART:
        // eslint-disable-next-line no-unused-expressions
        this.props.logExploreChart &&
          this.props.logExploreChart(this.props.slice.slice_id);
        break;
      case MENU_KEYS.EXPORT_CSV:
        // eslint-disable-next-line no-unused-expressions
        this.props.exportCSV && this.props.exportCSV(this.props.slice.slice_id);
        break;
      case MENU_KEYS.FULLSCREEN:
        this.props.handleToggleFullSize();
        break;
      case MENU_KEYS.EXPORT_FULL_CSV:
        // eslint-disable-next-line no-unused-expressions
        this.props.exportFullCSV &&
          this.props.exportFullCSV(this.props.slice.slice_id);
        break;
      case MENU_KEYS.DOWNLOAD_AS_IMAGE: {
        // menu closes with a delay, we need to hide it manually,
        // so that we don't capture it on the screenshot
        const menu = document.querySelector(
          '.ant-dropdown:not(.ant-dropdown-hidden)',
        ) as HTMLElement;
        menu.style.visibility = 'hidden';
        downloadAsImage(
          getScreenshotNodeSelector(this.props.slice.slice_id),
          this.props.slice.slice_name,
          true,
          // @ts-ignore
        )(domEvent).then(() => {
          menu.style.visibility = 'visible';
        });
        break;
      }
      default:
        break;
    }
  }

  render() {
    const {
      componentId,
      dashboardId,
      slice,
      isFullSize,
      cachedDttm = [],
      updatedDttm = null,
      addSuccessToast = () => {},
      addDangerToast = () => {},
      supersetCanShare = false,
      isCached = [],
    } = this.props;
    const crossFilterItems = getChartMetadataRegistry().items;
    const isTable = slice.viz_type === 'table';
    const isCrossFilter = Object.entries(crossFilterItems)
      // @ts-ignore
      .filter(([, { value }]) =>
        value.behaviors?.includes(Behavior.INTERACTIVE_CHART),
      )
      .find(([key]) => key === slice.viz_type);
    const canEmitCrossFilter = slice.form_data?.emit_filter;

    const cachedWhen = (cachedDttm || []).map(itemCachedDttm =>
      moment.utc(itemCachedDttm).fromNow(),
    );
    const updatedWhen = updatedDttm ? moment.utc(updatedDttm).fromNow() : '';
    const getCachedTitle = (itemCached: boolean) => {
      if (itemCached) {
        return t('Cached %s', cachedWhen);
      }
      if (updatedWhen) {
        return t('Fetched %s', updatedWhen);
      }
      return '';
    };
    const refreshTooltipData = [...new Set(isCached.map(getCachedTitle) || '')];
    // If all queries have same cache time we can unit them to one
    const refreshTooltip = refreshTooltipData.map((item, index) => (
      <div key={`tooltip-${index}`}>
        {refreshTooltipData.length > 1
          ? t('Query %s: %s', index + 1, item)
          : item}

    ));
    const fullscreenLabel = isFullSize
      ? t('Exit fullscreen')
      : t('Enter fullscreen');
    const menu = (
      <Menu
        onClick={this.handleMenuClick}
        selectable={false}
        data-test={`slice_${slice.slice_id}-menu`}
      >
        <Menu.Item
          key={MENU_KEYS.FORCE_REFRESH}
          disabled={this.props.chartStatus === 'loading'}
          style={{ height: 'auto', lineHeight: 'initial' }}
          data-test="refresh-chart-menu-item"
        >
          {t('Force refresh')}
          <RefreshTooltip data-test="dashboard-slice-refresh-tooltip">
            {refreshTooltip}
          </RefreshTooltip>
        </Menu.Item>

        <Menu.Item key={MENU_KEYS.FULLSCREEN}>{fullscreenLabel}</Menu.Item>

        <Menu.Divider />

        {slice.description && (
          <Menu.Item key={MENU_KEYS.TOGGLE_CHART_DESCRIPTION}>
            {this.props.isDescriptionExpanded
              ? t('Hide chart description')
              : t('Show chart description')}
          </Menu.Item>
        )}

        {this.props.supersetCanExplore && (
          <Menu.Item key={MENU_KEYS.EXPLORE_CHART}>
            <Link to={this.props.exploreUrl}>
              <Tooltip
                title={getSliceHeaderTooltip(this.props.slice.slice_name)}
              >
                {t('Edit chart')}
              </Tooltip>
            </Link>
          </Menu.Item>
        )}

        {this.props.supersetCanExplore && (
          <Menu.Item key={MENU_KEYS.VIEW_QUERY}>
            <ModalTrigger
              triggerNode={
                {t('View query')}
              }
              modalTitle={t('View query')}
              modalBody={
                <ViewQueryModal latestQueryFormData={this.props.formData} />
              }
              draggable
              resizable
              responsive
            />
          </Menu.Item>
        )}

        {this.props.supersetCanExplore && (
          <Menu.Item key={MENU_KEYS.VIEW_RESULTS}>
            <ModalTrigger
              triggerNode={

                  {t('View as table')}

              }
              modalTitle={t('Chart Data: %s', slice.slice_name)}
              modalBody={
                <ResultsPaneOnDashboard
                  queryFormData={this.props.formData}
                  queryForce={false}
                  dataSize={20}
                  isRequest
                  isVisible
                />
              }
              modalFooter={
                <Button
                  buttonStyle="secondary"
                  buttonSize="small"
                  onClick={() => this.props.history.push(this.props.exploreUrl)}
                >
                  {t('Edit chart')}
                </Button>
              }
              draggable
              resizable
              responsive
            />
          </Menu.Item>
        )}

        {(slice.description || this.props.supersetCanExplore) && (
          <Menu.Divider />
        )}

        {isFeatureEnabled(FeatureFlag.DASHBOARD_CROSS_FILTERS) &&
          isCrossFilter &&
          canEmitCrossFilter && (
            <>
              <Menu.Item key={MENU_KEYS.CROSS_FILTER_SCOPING}>
                {t('Cross-filter scoping')}
              </Menu.Item>
              <Menu.Divider />
            </>
          )}

        {supersetCanShare && (
          <Menu.SubMenu title={t('Share')}>
            <ShareMenuItems
              dashboardId={dashboardId}
              dashboardComponentId={componentId}
              copyMenuItemTitle={t('Copy permalink to clipboard')}
              emailMenuItemTitle={t('Share chart by email')}
              emailSubject={t('Superset chart')}
              emailBody={t('Check out this chart: ')}
              addSuccessToast={addSuccessToast}
              addDangerToast={addDangerToast}
            />
          </Menu.SubMenu>
        )}

        {this.props.slice.viz_type !== 'filter_box' &&
          this.props.supersetCanCSV && (
            <Menu.SubMenu title={t('Download')}>
              <Menu.Item
                key={MENU_KEYS.EXPORT_CSV}
                icon={<Icons.FileOutlined css={dropdownIconsStyles} />}
              >
                {t('Export to .CSV')}
              </Menu.Item>

              {this.props.slice.viz_type !== 'filter_box' &&
                isFeatureEnabled(FeatureFlag.ALLOW_FULL_CSV_EXPORT) &&
                this.props.supersetCanCSV &&
                isTable && (
                  <Menu.Item
                    key={MENU_KEYS.EXPORT_FULL_CSV}
                    icon={<Icons.FileOutlined css={dropdownIconsStyles} />}
                  >
                    {t('Export to full .CSV')}
                  </Menu.Item>
                )}

              <Menu.Item
                key={MENU_KEYS.DOWNLOAD_AS_IMAGE}
                icon={<Icons.FileImageOutlined css={dropdownIconsStyles} />}
              >
                {t('Download as image')}
              </Menu.Item>
            </Menu.SubMenu>
          )}
      </Menu>
    );

    return (
      <>
        <CrossFilterScopingModal
          chartId={slice.slice_id}
          isOpen={this.state.showCrossFilterScopingModal}
          onClose={() => this.setState({ showCrossFilterScopingModal: false })}
        />
        {isFullSize && (
          <Icons.FullscreenExitOutlined
            style={{ fontSize: 22 }}
            onClick={() => {
              this.props.handleToggleFullSize();
            }}
          />
        )}
        <NoAnimationDropdown
          overlay={menu}
          trigger={['click']}
          placement="bottomRight"
        >
          <span
            id={`slice_${slice.slice_id}-controls`}
            role="button"
            aria-label="More Options"
          >
            <VerticalDotsTrigger />

        </NoAnimationDropdown>
      </>
    );
  }
}

export default withRouter(SliceHeaderControls);


text:
#include <linux/kernel.h>
#include <linux/buffer_head.h>
#include <linux/string.h>

#include "befs.h"
#include "datastream.h"
#include "io.h"

const befs_inode_addr BAD_IADDR = { 0, 0, 0 };

static int befs_find_brun_direct(struct super_block *sb,
				 befs_data_stream * data,
				 befs_blocknr_t blockno, befs_block_run * run);

static int befs_find_brun_indirect(struct super_block *sb,
				   befs_data_stream * data,
				   befs_blocknr_t blockno,
				   befs_block_run * run);

static int befs_find_brun_dblindirect(struct super_block *sb,
				      befs_data_stream * data,
				      befs_blocknr_t blockno,
				      befs_block_run * run);

/**
 * befs_read_datastream - get buffer_head containing data, starting from pos.
 * @sb: Filesystem superblock
 * @ds: datastrem to find data with
 * @pos: start of data
 * @off: offset of data in buffer_head->b_data
 *
 * Returns pointer to buffer_head containing data starting with offset @off,
 * if you don't need to know offset just set @off = NULL.
 */
struct buffer_head *
befs_read_datastream(struct super_block *sb, befs_data_stream * ds,
		     befs_off_t pos, uint * off)
{
	struct buffer_head *bh = NULL;
	befs_block_run run;
	befs_blocknr_t block;	/* block coresponding to pos */

	befs_debug(sb, "---> %s %llu", __func__, pos);
	block = pos >> BEFS_SB(sb)->block_shift;
	if (off)
		*off = pos - (block << BEFS_SB(sb)->block_shift);

	if (befs_fblock2brun(sb, ds, block, &run) != BEFS_OK) {
		befs_error(sb, "BeFS: Error finding disk addr of block %lu",
			   (unsigned long)block);
		befs_debug(sb, "<--- %s ERROR", __func__);
		return NULL;
	}
	bh = befs_bread_iaddr(sb, run);
	if (!bh) {
		befs_error(sb, "BeFS: Error reading block %lu from datastream",
			   (unsigned long)block);
		return NULL;
	}

	befs_debug(sb, "<--- %s read data, starting at %llu", __func__, pos);

	return bh;
}

/*
 * Takes a file position and gives back a brun who's starting block
 * is block number fblock of the file.
 *
 * Returns BEFS_OK or BEFS_ERR.
 *
 * Calls specialized functions for each of the three possible
 * datastream regions.
 *
 * 2001-11-15 Will Dyson
 */
int
befs_fblock2brun(struct super_block *sb, befs_data_stream * data,
		 befs_blocknr_t fblock, befs_block_run * run)
{
	int err;
	befs_off_t pos = fblock << BEFS_SB(sb)->block_shift;

	if (pos < data->max_direct_range) {
		err = befs_find_brun_direct(sb, data, fblock, run);

	} else if (pos < data->max_indirect_range) {
		err = befs_find_brun_indirect(sb, data, fblock, run);

	} else if (pos < data->max_double_indirect_range) {
		err = befs_find_brun_dblindirect(sb, data, fblock, run);

	} else {
		befs_error(sb,
			   "befs_fblock2brun() was asked to find block %lu, "
			   "which is not mapped by the datastream\n",
			   (unsigned long)fblock);
		err = BEFS_ERR;
	}
	return err;
}

/**
 * befs_read_lsmylink - read long symlink from datastream.
 * @sb: Filesystem superblock
 * @ds: Datastrem to read from
 * @buff: Buffer in which to place long symlink data
 * @len: Length of the long symlink in bytes
 *
 * Returns the number of bytes read
 */
size_t
befs_read_lsymlink(struct super_block * sb, befs_data_stream * ds, void *buff,
		   befs_off_t len)
{
	befs_off_t bytes_read = 0;	/* bytes readed */
	u16 plen;
	struct buffer_head *bh = NULL;
	befs_debug(sb, "---> %s length: %llu", __func__, len);

	while (bytes_read < len) {
		bh = befs_read_datastream(sb, ds, bytes_read, NULL);
		if (!bh) {
			befs_error(sb, "BeFS: Error reading datastream block "
				   "starting from %llu", bytes_read);
			befs_debug(sb, "<--- %s ERROR", __func__);
			return bytes_read;

		}
		plen = ((bytes_read + BEFS_SB(sb)->block_size) < len) ?
		    BEFS_SB(sb)->block_size : len - bytes_read;
		memcpy(buff + bytes_read, bh->b_data, plen);
		brelse(bh);
		bytes_read += plen;
	}

	befs_debug(sb, "<--- %s read %u bytes", __func__, (unsigned int)
		   bytes_read);
	return bytes_read;
}

/**
 * befs_count_blocks - blocks used by a file
 * @sb: Filesystem superblock
 * @ds: Datastream of the file
 *
 * Counts the number of fs blocks that the file represented by
 * inode occupies on the filesystem, counting both regular file
 * data and filesystem metadata (and eventually attribute data
 * when we support attributes)
*/

befs_blocknr_t
befs_count_blocks(struct super_block * sb, befs_data_stream * ds)
{
	befs_blocknr_t blocks;
	befs_blocknr_t datablocks;	/* File data blocks */
	befs_blocknr_t metablocks;	/* FS metadata blocks */
	struct befs_sb_info *befs_sb = BEFS_SB(sb);

	befs_debug(sb, "---> %s", __func__);

	datablocks = ds->size >> befs_sb->block_shift;
	if (ds->size & (befs_sb->block_size - 1))
		datablocks += 1;

	metablocks = 1;		/* Start with 1 block for inode */

	/* Size of indirect block */
	if (ds->size > ds->max_direct_range)
		metablocks += ds->indirect.len;

	/*
	   Double indir block, plus all the indirect blocks it mapps
	   In the double-indirect range, all block runs of data are
	   BEFS_DBLINDIR_BRUN_LEN blocks long. Therefore, we know
	   how many data block runs are in the double-indirect region,
	   and from that we know how many indirect blocks it takes to
	   map them. We assume that the indirect blocks are also
	   BEFS_DBLINDIR_BRUN_LEN blocks long.
	 */
	if (ds->size > ds->max_indirect_range && ds->max_indirect_range != 0) {
		uint dbl_bytes;
		uint dbl_bruns;
		uint indirblocks;

		dbl_bytes =
		    ds->max_double_indirect_range - ds->max_indirect_range;
		dbl_bruns =
		    dbl_bytes / (befs_sb->block_size * BEFS_DBLINDIR_BRUN_LEN);
		indirblocks = dbl_bruns / befs_iaddrs_per_block(sb);

		metablocks += ds->double_indirect.len;
		metablocks += indirblocks;
	}

	blocks = datablocks + metablocks;
	befs_debug(sb, "<--- %s %u blocks", __func__, (unsigned int)blocks);

	return blocks;
}

/*
	Finds the block run that starts at file block number blockno
	in the file represented by the datastream data, if that
	blockno is in the direct region of the datastream.

	sb: the superblock
	data: the datastream
	blockno: the blocknumber to find
	run: The found run is passed back through this pointer

	Return value is BEFS_OK if the blockrun is found, BEFS_ERR
	otherwise.

	Algorithm:
	Linear search. Checks each element of array[] to see if it
	contains the blockno-th filesystem block. This is necessary
	because the block runs map variable amounts of data. Simply
	keeps a count of the number of blocks searched so far (sum),
	incrementing this by the length of each block run as we come
	across it. Adds sum to *count before returning (this is so
	you can search multiple arrays that are logicaly one array,
	as in the indirect region code).

	When/if blockno is found, if blockno is inside of a block
	run as stored on disk, we offset the start and length members
	of the block run, so that blockno is the start and len is
	still valid (the run ends in the same place).

	2001-11-15 Will Dyson
*/
static int
befs_find_brun_direct(struct super_block *sb, befs_data_stream * data,
		      befs_blocknr_t blockno, befs_block_run * run)
{
	int i;
	befs_block_run *array = data->direct;
	befs_blocknr_t sum;
	befs_blocknr_t max_block =
	    data->max_direct_range >> BEFS_SB(sb)->block_shift;

	befs_debug(sb, "---> %s, find %lu", __func__, (unsigned long)blockno);

	if (blockno > max_block) {
		befs_error(sb, "%s passed block outside of direct region",
			   __func__);
		return BEFS_ERR;
	}

	for (i = 0, sum = 0; i < BEFS_NUM_DIRECT_BLOCKS;
	     sum += array[i].len, i++) {
		if (blockno >= sum && blockno < sum + (array[i].len)) {
			int offset = blockno - sum;
			run->allocation_group = array[i].allocation_group;
			run->start = array[i].start + offset;
			run->len = array[i].len - offset;

			befs_debug(sb, "---> %s, "
				   "found %lu at direct[%d]", __func__,
				   (unsigned long)blockno, i);
			return BEFS_OK;
		}
	}

	befs_debug(sb, "---> %s ERROR", __func__);
	return BEFS_ERR;
}

/*
	Finds the block run that starts at file block number blockno
	in the file represented by the datastream data, if that
	blockno is in the indirect region of the datastream.

	sb: the superblock
	data: the datastream
	blockno: the blocknumber to find
	run: The found run is passed back through this pointer

	Return value is BEFS_OK if the blockrun is found, BEFS_ERR
	otherwise.

	Algorithm:
	For each block in the indirect run of the datastream, read
	it in and search through it for	search_blk.

	XXX:
	Really should check to make sure blockno is inside indirect
	region.

	2001-11-15 Will Dyson
*/
static int
befs_find_brun_indirect(struct super_block *sb,
			befs_data_stream * data, befs_blocknr_t blockno,
			befs_block_run * run)
{
	int i, j;
	befs_blocknr_t sum = 0;
	befs_blocknr_t indir_start_blk;
	befs_blocknr_t search_blk;
	struct buffer_head *indirblock;
	befs_disk_block_run *array;

	befs_block_run indirect = data->indirect;
	befs_blocknr_t indirblockno = iaddr2blockno(sb, &indirect);
	int arraylen = befs_iaddrs_per_block(sb);

	befs_debug(sb, "---> %s, find %lu", __func__, (unsigned long)blockno);

	indir_start_blk = data->max_direct_range >> BEFS_SB(sb)->block_shift;
	search_blk = blockno - indir_start_blk;

	/* Examine blocks of the indirect run one at a time */
	for (i = 0; i < indirect.len; i++) {
		indirblock = befs_bread(sb, indirblockno + i);
		if (indirblock == NULL) {
			befs_debug(sb, "---> %s failed to read "
				   "disk block %lu from the indirect brun",
				   __func__, (unsigned long)indirblockno + i);
			return BEFS_ERR;
		}

		array = (befs_disk_block_run *) indirblock->b_data;

		for (j = 0; j < arraylen; ++j) {
			int len = fs16_to_cpu(sb, array[j].len);

			if (search_blk >= sum && search_blk < sum + len) {
				int offset = search_blk - sum;
				run->allocation_group =
				    fs32_to_cpu(sb, array[j].allocation_group);
				run->start =
				    fs16_to_cpu(sb, array[j].start) + offset;
				run->len =
				    fs16_to_cpu(sb, array[j].len) - offset;

				brelse(indirblock);
				befs_debug(sb,
					   "<--- %s found file block "
					   "%lu at indirect[%d]", __func__,
					   (unsigned long)blockno,
					   j + (i * arraylen));
				return BEFS_OK;
			}
			sum += len;
		}

		brelse(indirblock);
	}

	/* Only fallthrough is an error */
	befs_error(sb, "BeFS: %s failed to find "
		   "file block %lu", __func__, (unsigned long)blockno);

	befs_debug(sb, "<--- %s ERROR", __func__);
	return BEFS_ERR;
}

/*
	Finds the block run that starts at file block number blockno
	in the file represented by the datastream data, if that
	blockno is in the double-indirect region of the datastream.

	sb: the superblock
	data: the datastream
	blockno: the blocknumber to find
	run: The found run is passed back through this pointer

	Return value is BEFS_OK if the blockrun is found, BEFS_ERR
	otherwise.

	Algorithm:
	The block runs in the double-indirect region are different.
	They are always allocated 4 fs blocks at a time, so each
	block run maps a constant amount of file data. This means
	that we can directly calculate how many block runs into the
	double-indirect region we need to go to get to the one that
	maps a particular filesystem block.

	We do this in two stages. First we calculate which of the
	inode addresses in the double-indirect block will point us
	to the indirect block that contains the mapping for the data,
	then we calculate which of the inode addresses in that
	indirect block maps the data block we are after.

	Oh, and once we've done that, we actually read in the blocks
	that contain the inode addresses we calculated above. Even
	though the double-indirect run may be several blocks long,
	we can calculate which of those blocks will contain the index
	we are after and only read that one. We then follow it to
	the indirect block and perform a  similar process to find
	the actual block run that maps the data block we are interested
	in.

	Then we offset the run as in befs_find_brun_array() and we are
	done.

	2001-11-15 Will Dyson
*/
static int
befs_find_brun_dblindirect(struct super_block *sb,
			   befs_data_stream * data, befs_blocknr_t blockno,
			   befs_block_run * run)
{
	int dblindir_indx;
	int indir_indx;
	int offset;
	int dbl_which_block;
	int which_block;
	int dbl_block_indx;
	int block_indx;
	off_t dblindir_leftover;
	befs_blocknr_t blockno_at_run_start;
	struct buffer_head *dbl_indir_block;
	struct buffer_head *indir_block;
	befs_block_run indir_run;
	befs_disk_inode_addr *iaddr_array = NULL;
	struct befs_sb_info *befs_sb = BEFS_SB(sb);

	befs_blocknr_t indir_start_blk =
	    data->max_indirect_range >> befs_sb->block_shift;

	off_t dbl_indir_off = blockno - indir_start_blk;

	/* number of data blocks mapped by each of the iaddrs in
	 * the indirect block pointed to by the double indirect block
	 */
	size_t iblklen = BEFS_DBLINDIR_BRUN_LEN;

	/* number of data blocks mapped by each of the iaddrs in
	 * the double indirect block
	 */
	size_t diblklen = iblklen * befs_iaddrs_per_block(sb)
	    * BEFS_DBLINDIR_BRUN_LEN;

	befs_debug(sb, "---> %s find %lu", __func__, (unsigned long)blockno);

	/* First, discover which of the double_indir->indir blocks
	 * contains pos. Then figure out how much of pos that
	 * accounted for. Then discover which of the iaddrs in
	 * the indirect block contains pos.
	 */

	dblindir_indx = dbl_indir_off / diblklen;
	dblindir_leftover = dbl_indir_off % diblklen;
	indir_indx = dblindir_leftover / diblklen;

	/* Read double indirect block */
	dbl_which_block = dblindir_indx / befs_iaddrs_per_block(sb);
	if (dbl_which_block > data->double_indirect.len) {
		befs_error(sb, "The double-indirect index calculated by "
			   "%s, %d, is outside the range "
			   "of the double-indirect block", __func__,
			   dblindir_indx);
		return BEFS_ERR;
	}

	dbl_indir_block =
	    befs_bread(sb, iaddr2blockno(sb, &data->double_indirect) +
					dbl_which_block);
	if (dbl_indir_block == NULL) {
		befs_error(sb, "%s couldn't read the "
			   "double-indirect block at blockno %lu", __func__,
			   (unsigned long)
			   iaddr2blockno(sb, &data->double_indirect) +
			   dbl_which_block);
		brelse(dbl_indir_block);
		return BEFS_ERR;
	}

	dbl_block_indx =
	    dblindir_indx - (dbl_which_block * befs_iaddrs_per_block(sb));
	iaddr_array = (befs_disk_inode_addr *) dbl_indir_block->b_data;
	indir_run = fsrun_to_cpu(sb, iaddr_array[dbl_block_indx]);
	brelse(dbl_indir_block);
	iaddr_array = NULL;

	/* Read indirect block */
	which_block = indir_indx / befs_iaddrs_per_block(sb);
	if (which_block > indir_run.len) {
		befs_error(sb, "The indirect index calculated by "
			   "%s, %d, is outside the range "
			   "of the indirect block", __func__, indir_indx);
		return BEFS_ERR;
	}

	indir_block =
	    befs_bread(sb, iaddr2blockno(sb, &indir_run) + which_block);
	if (indir_block == NULL) {
		befs_error(sb, "%s couldn't read the indirect block "
			   "at blockno %lu", __func__, (unsigned long)
			   iaddr2blockno(sb, &indir_run) + which_block);
		brelse(indir_block);
		return BEFS_ERR;
	}

	block_indx = indir_indx - (which_block * befs_iaddrs_per_block(sb));
	iaddr_array = (befs_disk_inode_addr *) indir_block->b_data;
	*run = fsrun_to_cpu(sb, iaddr_array[block_indx]);
	brelse(indir_block);
	iaddr_array = NULL;

	blockno_at_run_start = indir_start_blk;
	blockno_at_run_start += diblklen * dblindir_indx;
	blockno_at_run_start += iblklen * indir_indx;
	offset = blockno - blockno_at_run_start;

	run->start += offset;
	run->len -= offset;

	befs_debug(sb, "Found file block %lu in double_indirect[%d][%d],"
		   " double_indirect_leftover = %lu", (unsigned long)
		   blockno, dblindir_indx, indir_indx, dblindir_leftover);

	return BEFS_OK;
}


text:
package org.cinnamon.core.exception;

/**
 *
 * @author dsshin
 * created date: 2014. 4. 21.
 */
public class BadRequestException extends BaseException {

	/**
	 *
	 */
	private static final long serialVersionUID = 3773883653794586404L;

	public BadRequestException() {
		super();
	}

	public BadRequestException(String message) {
		super(message);
	}

	@Override
	public String getErrorCode() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public String getDescription() {
		// TODO Auto-generated method stub
		return null;
	}

}


text:
/**
 * @class Oskari.mapframework.bundle.toolbar.request.ToolbarRequest
 * Requests for toolbar to create/show/hide/remove a toolbar.
 *
 * Requests are build and sent through Oskari.mapframework.sandbox.Sandbox.
 * Oskari.mapframework.request.Request superclass documents how to send one.
 */
Oskari.clazz.define('Oskari.mapframework.bundle.toolbar.request.ToolbarRequest',
    /**
     * @method create called automatically on construction
     * @static
     *
     * @param {String}
     *            id identifier so we can manage the toolbars buttons with subsequent requests
     * @param {String}
     *            op operation 'add', 'remove','show' or 'hide'
     * @param {Object}
     *            data operation arguments as properties
     */

    function (id, op, data) {
        this._id = id;
        this._op = op;
        this._data = data;
    }, {
        /** @static @property __name request name */
        __name: "Toolbar.ToolbarRequest",
        /**
         * @method getName
         * @return {String} request name
         */
        getName: function () {
            return this.__name;
        },

        /**
         * @method getId
         * @return {String} identifier so we can manage the button with subsequent requests
         */
        getId: function () {
            return this._id;
        },
        /**
         * @method getGroup
         * @return {String} identifier for organizing buttons
         */
        getOp: function () {
            return this._op;
        },

        /**
         * @method getData
         * @return {Object} the properties for requested operation
         */
        getData: function () {
            return this._data;
        }

    }, {
        'protocol': ['Oskari.mapframework.request.Request']
    });

/* Inheritance */


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="author" content="">

    <title>eFile Your Small Claim</title>

    <link href="css/bootstrap.min.css" rel="stylesheet">

     <link href="http://netdna.bootstrapcdn.com/bootstrap/3.1.0/css/bootstrap.min.css" rel="stylesheet">

    <link href="font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css">
    <link href="http://fonts.googleapis.com/css?family=Lato:300,400,700,300italic,400italic,700italic" rel="stylesheet" type="text/css">

    <link rel="stylesheet" href="j-folder/css/demo.css">
	<link rel="stylesheet" href="j-folder/css/font-awesome.min.css">
	<link rel="stylesheet" href="j-folder/css/j-forms.css">
    <link href="css/landing-page.css" rel="stylesheet">

                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
                    Toggle navigation

                </button>

                        Call Us

                        About

                        Services

                        Start an eFile

Smallclaim.com

Turn Your Dispute Into Dollars

With The Experts of Smallclaim.com

                                 Speak to an Expert About Your Case

                                 Complete eFile in 15 min.

                                 Start Your Claim Application

Before You've Filed:
We'll Show You Your Options for Free!

Let Our Qualified Small Claim Specialists Help You Save Time, Avoid High Attorney Fees, And Help You Get All the Money Owed to You - Quickly & Easily

                        Learn More

After Filing:
We Have Services for Every Situation

Reviewing each case

Preparing the small claims documents

File the claim with the proper court

Serve the defendant at his/her home or business

File proof(s) of Services with the court

Don't wait any longer, let us help you file your claim and turn your dispute into dollars today!

                        Contact Us

After Winning:
We Help You Get Your $

This is our specialty! We'll help you track down assets, accounts, individuals and anything else in pursuit of your money!

                        Contact Us to Learn How

Have Plaintiff and Defendant Contact Info?

                      5 Minute eFile!

Need Help Filing or Finding Necessary Info?

                      Contact An Expert, Free!

                                    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>

 Any questions? Feel free to contact us.

                                    <form accept-charset="UTF-8" action="https://zi261.infusionsoft.com/app/form/process/50ce6e8722f533e146c79add0bba942e" class="infusion-form" method="POST">
                                    <input name="inf_form_xid" type="hidden" value="50ce6e8722f533e146c79add0bba942e">
                                    <input name="inf_form_name" type="hidden" value="Express Landing Page Form">
                                    <input name="infusionsoft_version" type="hidden" value="1.44.0.47">
                                    <input class="form-control input-box" id="inf_field_FirstName" type="text" name="inf_field_FirstName" placeholder="First Name">
                                    <input class="form-control input-box" id="inf_field_LastName" type="text" name="inf_field_LastName" placeholder="Last Name">
                                    <input class="form-control input-box" id="inf_field_Email" type="email" name="inf_field_Email" placeholder="Your Email">
                                    <input class="form-control input-box" id="inf_field_Phone1" type="text" name="inf_field_Phone1" placeholder="Phone Number">

                                        <select id="inf_custom_ServiceSelect" name="inf_custom_ServiceSelect"><option value="">Please select one</option><option value="I want to file a new claim.">I want to file a new claim.</option><option value="Done filing need additional help.">Done filing need additional help.</option><option value="Done with trail tracking payments.">Done with trail tracking payments.</option><option value="I'm calling for a consultation">I'm calling for a consultation</option>                                       </select>

                                              <button style="text-align: center;" type="submit" class="btn btn-default" value="Send">Send</button>
                                                <button style="float: right;" type="button" class="btn btn-default btn-close" data-dismiss="modal" value="Send">Close</button>

                                    </form>

                            Home

⋅

                            About

⋅

                            Services

⋅

                            Contact

Copyright © Smallclaim.com 2015. All Rights Reserved


text:
using System;
using NServiceBus.OutgoingPipeline;
using NServiceBus.TransportDispatch;

#region outgoing-header-behavior

class OutgoingHeaderBehavior : PhysicalOutgoingContextStageBehavior
{
    public override void Invoke(Context context, Action next)
    {
        context.SetHeader("OutgoingHeaderBehavior", "ValueOutgoingHeaderBehavior");
        next();
    }
}

#endregion


text:
#import "FPAppDelegate.h"
#import "DataModel.h"
#import "ExampleTableViewController.h"

@implementation FPAppDelegate

@synthesize managedObjectContext = _managedObjectContext;
@synthesize managedObjectModel = _managedObjectModel;
@synthesize persistentStoreCoordinator = _persistentStoreCoordinator;

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];

    [DataModel main].managedObjectContext = self.managedObjectContext;
    [[DataModel main] taskWithName:@"Milk" complete:NO ordering:0];
    [[DataModel main] taskWithName:@"Eggs" complete:NO ordering:1];
    [[DataModel main] taskWithName:@"Newspaper" complete:YES ordering:2];

    ExampleTableViewController *tableViewController = [[ExampleTableViewController alloc] initWithStyle:UITableViewStylePlain];
    UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:tableViewController];
    [self.window setRootViewController:navController];

    self.window.backgroundColor = [UIColor whiteColor];
    [self.window makeKeyAndVisible];
    return YES;
}

- (void)applicationWillTerminate:(UIApplication *)application
{
    [self saveContext];
}

- (void)saveContext
{
    NSError *error = nil;
    NSManagedObjectContext *managedObjectContext = self.managedObjectContext;
    if (managedObjectContext != nil) {
        if ([managedObjectContext hasChanges] && ![managedObjectContext save:&error]) {
            NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
            abort();
        }
    }
}

#pragma mark - Core Data stack

- (NSManagedObjectContext *)managedObjectContext
{
    if (_managedObjectContext != nil) {
        return _managedObjectContext;
    }

    NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
    if (coordinator != nil) {
        _managedObjectContext = [[NSManagedObjectContext alloc] init];
        [_managedObjectContext setPersistentStoreCoordinator:coordinator];
    }
    return _managedObjectContext;
}

- (NSManagedObjectModel *)managedObjectModel
{
    if (_managedObjectModel != nil) {
        return _managedObjectModel;
    }
    NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"FPMultiFetchedResultsControllerExample" withExtension:@"momd"];
    _managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
    return _managedObjectModel;
}

- (NSPersistentStoreCoordinator *)persistentStoreCoordinator
{
    if (_persistentStoreCoordinator != nil) {
        return _persistentStoreCoordinator;
    }

    NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"FPMultiFetchedResultsControllerExample.sqlite"];

    NSError *error = nil;
    _persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
    if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]) {
        NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
        abort();
    }

    return _persistentStoreCoordinator;
}

#pragma mark - Application's Documents directory

- (NSURL *)applicationDocumentsDirectory
{
    return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
}

@end


text:
/* vim: se cin sw=2 ts=2 et : */
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

#ifndef __mozilla_widget_GfxInfo_h__
#define __mozilla_widget_GfxInfo_h__

#include "GfxInfoBase.h"
#include "GfxDriverInfo.h"

#include "nsString.h"

namespace mozilla {
namespace widget {

class GfxInfo : public GfxInfoBase
{
public:
  GfxInfo();

  // We only declare the subset of nsIGfxInfo that we actually implement. The
  // rest is brought forward from GfxInfoBase.
  NS_IMETHOD GetD2DEnabled(bool *aD2DEnabled);
  NS_IMETHOD GetDWriteEnabled(bool *aDWriteEnabled);
  NS_IMETHOD GetDWriteVersion(nsAString & aDwriteVersion);
  NS_IMETHOD GetCleartypeParameters(nsAString & aCleartypeParams);
  NS_IMETHOD GetAdapterDescription(nsAString & aAdapterDescription);
  NS_IMETHOD GetAdapterDriver(nsAString & aAdapterDriver);
  NS_IMETHOD GetAdapterVendorID(nsAString & aAdapterVendorID);
  NS_IMETHOD GetAdapterDeviceID(nsAString & aAdapterDeviceID);
  NS_IMETHOD GetAdapterRAM(nsAString & aAdapterRAM);
  NS_IMETHOD GetAdapterDriverVersion(nsAString & aAdapterDriverVersion);
  NS_IMETHOD GetAdapterDriverDate(nsAString & aAdapterDriverDate);
  NS_IMETHOD GetAdapterDescription2(nsAString & aAdapterDescription);
  NS_IMETHOD GetAdapterDriver2(nsAString & aAdapterDriver);
  NS_IMETHOD GetAdapterVendorID2(nsAString & aAdapterVendorID);
  NS_IMETHOD GetAdapterDeviceID2(nsAString & aAdapterDeviceID);
  NS_IMETHOD GetAdapterRAM2(nsAString & aAdapterRAM);
  NS_IMETHOD GetAdapterDriverVersion2(nsAString & aAdapterDriverVersion);
  NS_IMETHOD GetAdapterDriverDate2(nsAString & aAdapterDriverDate);
  NS_IMETHOD GetIsGPU2Active(bool *aIsGPU2Active);
  using GfxInfoBase::GetFeatureStatus;
  using GfxInfoBase::GetFeatureSuggestedDriverVersion;
  using GfxInfoBase::GetWebGLParameter;

  void EnsureInitializedFromGfxInfoData();

  virtual const nsAString& Model() const;
  virtual const nsAString& Hardware() const;
  virtual const nsAString& Product() const;
  virtual const nsAString& Manufacturer() const;

#ifdef DEBUG
  NS_DECL_ISUPPORTS_INHERITED
  NS_DECL_NSIGFXINFODEBUG
#endif

  virtual uint32_t OperatingSystemVersion() const { return mOSVersion; }

protected:

  virtual nsresult GetFeatureStatusImpl(int32_t aFeature,
                                        int32_t *aStatus,
                                        nsAString & aSuggestedDriverVersion,
                                        const nsTArray<GfxDriverInfo>& aDriverInfo,
                                        OperatingSystem* aOS = nullptr);
  virtual const nsTArray<GfxDriverInfo>& GetGfxDriverInfo();

private:

  void AddCrashReportAnnotations();

  bool mInitializedFromJavaData;

  // the GL strings
  nsCString mVendor;
  nsCString mRenderer;
  nsCString mVersion;
  // a possible error message produced by the data source (e.g. if EGL initialization failed)
  nsCString mError;

  nsCString mAdapterDescription;

  OperatingSystem mOS;
  uint32_t mOSVersion;

  nsString mModel, mHardware, mManufacturer, mProduct;
};

} // namespace widget
} // namespace mozilla

#endif /* __mozilla_widget_GfxInfo_h__ */