text:
OGImage
=======

## Introduction

The idea behind `OGImage` is to encapsulate best practices for loading images
over HTTP in a simple, extensible interface.

### Philosophy

* The default use case should be *ridiculously* simple to execute. In OGImage,
  you can load, cache, and scale an image with the following call:

    ```objc
    OGScaledImage *ogImage = [[OGScaledImage alloc] initWithURL:imageURL size:renderSize key:nil];
    [ogImage addObserver:self forKey:@"scaledImage" options:NSKeyValueObservingOptionNew context:nil];
    // there is no step 3!
    ```

* Networking belongs in the Model. Views (and to some degree, Controllers)
  shouldn't know anything about where images come from: That's the model's job.
  OGImage is designed as a model object: Controllers and Views learn about
  changes to it (e.g., when an image has loaded) through KVO.
* Generally, more recently requested images should have higher loading
  priority. For example, if images are being loaded on demand as a user scrolls
  through a table view, the user experience is improved if they don't have to
  wait for all the images they've scrolled past to load before the images that
  are visible are loaded. At the same time, we don't believe in waiting until a
  table view has finished scrolling to start loading images.  OGImage addresses
  these competing requirements by pushing image load requests into a LIFO
  queue.
* Each subsystem should have its own GCD queue.

## Installation

To use OGImage in your projects, simply add the files in the `OGImage`
subdirectory to your target.

If you're using `OGScaledImage` and/or `OGImageProcessing`, you'll need to add
`Accelerate.framework` to your target's "Link Binary With Libraries" build
phase.

## Usage

OGImage has a simple interface; just instantiate with the image's URL and
listen for KVO notifications on the `image` property. You can also specify a
placeholder image to use until loading is complete with
`initWithURL:placeholderImage`

```objc
#import "OGImage.h"

...

OGImage *image = [[OGImage alloc] initWithURL:[NSURL URLWithString:@"http://somedomain.com/someimage.jpg"]];
[image addObserver:self forKeyPath:@"image" options:NSKeyValueObservingOptionNew context:nil];

...

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    if ([keyPath isEqualToString:@"image"]) {
        // image was loaded!
        ...
    } else if ([keyPath isEqualToString:@"error"]) {
        // error loading image
    }
}
```

There are also caching (`OGCachedImage`) and caching+scaling (`OGScaledImage`)
subclasses that provide useful functionality and demonstrate how to go about
bending OGImage to your needs via subclassing.

```objc

#import "OGScaledImage.h"

/*
 * The image at `imageURL` will be loaded from one of in-memory cache, disk cache or
 * over the network and scaled to `scaledSize`. Note that if the image at `imageURL`
 * has already been scaled to `scaledSize` in the past, OGScaledImage will simply
 * load the scaled image from cache.
 */
OGScaledImage *image = [[OGScaledImage alloc] initWithURL:imageURL size:scaledSize key:nil];

/*
 * Note that here we're interested in the `scaledImage` property, not the full-size `image`
 * property.
 */
[image addObserver:self forKeyPath:@"scaledImage" options:NSKeyValueObservingOptionNew context:nil];

...

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    if ([keyPath isEqualToString:@"scaledImage"]) {
        // image was loaded and scaled!
        ...
    } else if ([keyPath isEqualToString:@"error"]) {
        // error loading image
    }
}
```

## Demo and Tests

This repo contains a very simple project that demonstrates the use of
`OGScaledImage` with a stock `UITableView`.

To run the demo and tests in the `OGImageDemo project`, you'll need
[CocoaPods](http://cocoapods.org/) If you already have cocoapods on your
system, just run `pod install` from the terminal in the `OGImageDemo`
directory.

Note that you *do not* need cocoapods to use `OGImage` in your projects--there
are no external dependencies for the library itself, only for the tests
(GHUnit) and demo (CocoaLumberjack)

## TODO:

* Sexier demo app, maybe something `UICollectionView`-based.
* More image processing operations, e.g., adding rounded corners, b&w, etc.
* More test coverage.


text:
<script src="/socket.io/socket.io.js"></script>
<script>
    var socket = io.connect('http://localhost:3000');
        socket.on('news', function (data) {
            console.log(data);
            socket.emit('some event', { my: 'data' });
        });
</script>

redpajama_set_name: RedPajamaGithub


text:
<?php declare(strict_types=1);

namespace Pharaoh\Tests;

use Pharaoh\Config\ConfigInterface;
use Pharaoh\Tests\Fixtures\PharaohForTest;

/**
 * @coversDefaultClass \Pharaoh\Pharaoh
 */
class PharaohTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @covers ::__construct
     * @covers ::getStartTime
     * @covers ::isProfilerEnabled
     */
    public function testConstructor()
    {
        $profile = true;
        $name    = 'PharaohTest';
        $config  = $this->createMock(ConfigInterface::class);

        $pharaoh = new PharaohForTest($config, $name, $profile);

        $this->assertEquals($profile, $pharaoh->isProfilerEnabled());
        $this->assertFalse($pharaoh->isBooted());
        $this->assertLessThan(microtime(true), $pharaoh->getStartTime());
    }

    /**
     * @covers ::__clone
     * @covers ::getStartTime
     * @covers ::isProfilerEnabled
     *
     * @uses \Pharaoh\Pharaoh::__construct
     */
    public function testClone()
    {
        $profile = true;
        $name    = 'PharaohTest';
        $config  = $this->createMock(ConfigInterface::class);

        $pharaoh = new PharaohForTest($config, $name, $profile);

        $clone = clone $pharaoh;

        $this->assertEquals($profile, $clone->isProfilerEnabled());
        $this->assertFalse($clone->isBooted());
        $this->assertLessThan(microtime(true), $clone->getStartTime());
        $this->assertLessThan($clone->getStartTime(), $pharaoh->getStartTime());
    }

    /**
     * @covers ::getConfigDirectory
     *
     * @uses \Pharaoh\Pharaoh::__construct
     */
    public function testGetConfigDirectory()
    {
        $profile = true;
        $name    = 'PharaohTest';
        $config  = $this->createMock(ConfigInterface::class);

        $configDir = 'ConfigDirectory';

        $config
            ->expects($this->once())
            ->method('getConfigDirectory')
            ->will($this->returnValue($configDir))
        ;

        $pharaoh = new PharaohForTest($config, $name, $profile);

        $this->assertEquals($configDir, $pharaoh->getConfigDirectory());
    }

    /**
     * @covers ::getCacheDirectory
     *
     * @uses \Pharaoh\Pharaoh::__construct
     */
    public function testGetCacheDirectory()
    {
        $profile = true;
        $name    = 'PharaohTest';
        $config  = $this->createMock(ConfigInterface::class);

        $cacheDir = 'CacheDirectory';

        $config
            ->expects($this->once())
            ->method('getCacheDirectory')
            ->will($this->returnValue($cacheDir))
        ;

        $pharaoh = new PharaohForTest($config, $name, $profile);

        $this->assertEquals($cacheDir, $pharaoh->getCacheDirectory());
    }

    /**
     * @covers ::getLogDirectory
     *
     * @uses \Pharaoh\Pharaoh::__construct
     */
    public function testGetLogDirectory()
    {
        $profile = true;
        $name    = 'PharaohTest';
        $config  = $this->createMock(ConfigInterface::class);

        $logDir = 'LogDirectory';

        $config
            ->expects($this->once())
            ->method('getLogDirectory')
            ->will($this->returnValue($logDir))
        ;

        $pharaoh = new PharaohForTest($config, $name, $profile);

        $this->assertEquals($logDir, $pharaoh->getLogDirectory());
    }
}


text:
package org.ovirt.engine.core.bll.storage;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.when;

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

import org.junit.ClassRule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.runners.MockitoJUnitRunner;
import org.mockito.stubbing.Answer;
import org.ovirt.engine.core.bll.context.CommandContext;
import org.ovirt.engine.core.bll.context.CompensationContext;
import org.ovirt.engine.core.bll.interfaces.BackendInternal;
import org.ovirt.engine.core.common.action.AttachStorageDomainToPoolParameters;
import org.ovirt.engine.core.common.action.VdcActionParametersBase;
import org.ovirt.engine.core.common.action.VdcActionType;
import org.ovirt.engine.core.common.action.VdcReturnValueBase;
import org.ovirt.engine.core.common.businessentities.OvfEntityData;
import org.ovirt.engine.core.common.businessentities.StorageDomain;
import org.ovirt.engine.core.common.businessentities.StorageDomainStatic;
import org.ovirt.engine.core.common.businessentities.StorageDomainStatus;
import org.ovirt.engine.core.common.businessentities.StorageDomainType;
import org.ovirt.engine.core.common.businessentities.StoragePool;
import org.ovirt.engine.core.common.businessentities.StoragePoolIsoMap;
import org.ovirt.engine.core.common.businessentities.StoragePoolIsoMapId;
import org.ovirt.engine.core.common.businessentities.StoragePoolStatus;
import org.ovirt.engine.core.common.businessentities.VDS;
import org.ovirt.engine.core.common.businessentities.VDSStatus;
import org.ovirt.engine.core.common.interfaces.VDSBrokerFrontend;
import org.ovirt.engine.core.common.utils.Pair;
import org.ovirt.engine.core.common.vdscommands.AttachStorageDomainVDSCommandParameters;
import org.ovirt.engine.core.common.vdscommands.HSMGetStorageDomainInfoVDSCommandParameters;
import org.ovirt.engine.core.common.vdscommands.VDSCommandType;
import org.ovirt.engine.core.common.vdscommands.VDSReturnValue;
import org.ovirt.engine.core.compat.Guid;
import org.ovirt.engine.core.dal.dbbroker.DbFacade;
import org.ovirt.engine.core.dao.StorageDomainDAO;
import org.ovirt.engine.core.dao.StorageDomainStaticDAO;
import org.ovirt.engine.core.dao.StoragePoolDAO;
import org.ovirt.engine.core.dao.StoragePoolIsoMapDAO;
import org.ovirt.engine.core.dao.VdsDAO;
import org.ovirt.engine.core.utils.MockEJBStrategyRule;

@RunWith(MockitoJUnitRunner.class)
public class AttachStorageDomainToPoolCommandTest {
    @Mock
    private DbFacade dbFacade;
    @Mock
    private StoragePoolIsoMapDAO isoMapDAO;
    @Mock
    private StoragePoolDAO storagePoolDAO;
    @Mock
    private StorageDomainDAO storageDomainDAO;
    @Mock
    private StorageDomainStaticDAO storageDomainStaticDAO;
    @Mock
    private VdsDAO vdsDAO;
    @Mock
    private BackendInternal backendInternal;
    @Mock
    private VDSBrokerFrontend vdsBrokerFrontend;
    @Mock
    private VDS vds;
    StoragePoolIsoMap map = null;

    @ClassRule
    public static MockEJBStrategyRule mockEjbRule = new MockEJBStrategyRule();

    @Test
    public void statusSetInMap() {
        AttachStorageDomainToPoolParameters params =
                new AttachStorageDomainToPoolParameters(Guid.newGuid(), Guid.newGuid());
        AttachStorageDomainToPoolCommand<AttachStorageDomainToPoolParameters> cmd =
                spy(new AttachStorageDomainToPoolCommand<AttachStorageDomainToPoolParameters>(params));

        doReturn(dbFacade).when(cmd).getDbFacade();
        doNothing().when(cmd).attemptToActivateDomain();

        when(dbFacade.getStoragePoolIsoMapDao()).thenReturn(isoMapDAO);
        when(dbFacade.getStoragePoolDao()).thenReturn(storagePoolDAO);
        when(dbFacade.getVdsDao()).thenReturn(vdsDAO);
        when(dbFacade.getStorageDomainDao()).thenReturn(storageDomainDAO);
        when(dbFacade.getStorageDomainStaticDao()).thenReturn(storageDomainStaticDAO);
        StoragePool pool = new StoragePool();
        pool.setStatus(StoragePoolStatus.Up);
        when(storagePoolDAO.get(any(Guid.class))).thenReturn(pool);
        when(isoMapDAO.get(any(StoragePoolIsoMapId.class))).thenReturn(map);
        when(storageDomainDAO.getForStoragePool(any(Guid.class), any(Guid.class))).thenReturn(new StorageDomain());
        when(storageDomainStaticDAO.get(any(Guid.class))).thenReturn(new StorageDomainStatic());

        doReturn(backendInternal).when(cmd).getBackend();
        when(vdsDAO.getAllForStoragePoolAndStatus(any(Guid.class), any(VDSStatus.class))).thenReturn(new ArrayList<VDS>());
        when(backendInternal.getResourceManager()).thenReturn(vdsBrokerFrontend);
        VdcReturnValueBase vdcReturnValue = new VdcReturnValueBase();
        vdcReturnValue.setSucceeded(true);
        when(backendInternal.runInternalAction(any(VdcActionType.class),
                any(VdcActionParametersBase.class),
                any(CommandContext.class))).thenReturn(vdcReturnValue);
        StorageDomainStatic storageDomain = new StorageDomainStatic();
        storageDomain.setId(Guid.newGuid());
        storageDomain.setStorageDomainType(StorageDomainType.ImportExport);
        mockGetStorageDomainInfoVdsCommand(storageDomain);
        mockAttachStorageDomainVdsCommand();
        when(vdsDAO.get(any(Guid.class))).thenReturn(vds);
        doReturn(getUnregisteredList()).when(cmd).getEntitiesFromStorageOvfDisk();
        doAnswer(new Answer<Object>() {
            @Override
            public Object answer(InvocationOnMock invocation) throws Throwable {
                map = (StoragePoolIsoMap) invocation.getArguments()[0];
                return null;
            }
        }).when(isoMapDAO).save(any(StoragePoolIsoMap.class));

        cmd.setCompensationContext(mock(CompensationContext.class));
        cmd.executeCommand();
        assertNotNull(map);
        assertEquals(StorageDomainStatus.Maintenance, map.getStatus());
    }

    private void mockAttachStorageDomainVdsCommand() {
        VDSReturnValue returnValue = new VDSReturnValue();
        returnValue.setSucceeded(true);
        when(vdsBrokerFrontend.RunVdsCommand(eq(VDSCommandType.AttachStorageDomain),
                any(AttachStorageDomainVDSCommandParameters.class))).thenReturn(returnValue);
    }

    private void mockGetStorageDomainInfoVdsCommand(StorageDomainStatic storageDomain) {
        Pair<StorageDomainStatic, Guid> pairResult = new Pair<>(storageDomain, null);
        VDSReturnValue returnValueForGetStorageDomainInfo = new VDSReturnValue();
        returnValueForGetStorageDomainInfo.setSucceeded(true);
        returnValueForGetStorageDomainInfo.setReturnValue(pairResult);
        when(vdsBrokerFrontend.RunVdsCommand(eq(VDSCommandType.HSMGetStorageDomainInfo),
                any(HSMGetStorageDomainInfoVDSCommandParameters.class))).thenReturn(returnValueForGetStorageDomainInfo);
    }

    private List<OvfEntityData> getUnregisteredList() {
        return new ArrayList<OvfEntityData>();
    }
}


text:
/*
 * test_spiffs.h
 *
 *  Created on: Jun 19, 2013
 *      Author: petera
 */

#ifndef TEST_SPIFFS_H_
#define TEST_SPIFFS_H_

#include "spiffs.h"

#define FS &__fs

extern spiffs __fs;

#define CHECK(r) if (!(r)) return -1;
#define CHECK_RES(r) if (r < 0) return -1;
#define FS_PURE_DATA_PAGES(fs) \
    ((fs)->cfg.phys_size / (fs)->cfg.log_page_size - (fs)->block_count * SPIFFS_OBJ_LOOKUP_PAGES(fs))
#define FS_PURE_DATA_SIZE(fs) \
    FS_PURE_DATA_PAGES(fs) * SPIFFS_DATA_PAGE_SIZE(fs)

typedef enum {
  EMPTY,
  SMALL,
  MEDIUM,
  LARGE,
} tfile_size;

typedef enum {
  UNTAMPERED,
  APPENDED,
  MODIFIED,
  REWRITTEN,
} tfile_type;

typedef enum {
  SHORT = 3,
  NORMAL = 15,
  LONG = 100,
} tfile_life;

typedef struct  {
  tfile_size tsize;
  tfile_type ttype;
  tfile_life tlife;
} tfile_conf;

typedef struct  {
  int state;
  spiffs_file fd;
  tfile_conf cfg;
  char name[32];
} tfile;

void fs_reset();
void fs_reset_specific(u32_t addr_offset, u32_t phys_addr, u32_t phys_size,
    u32_t phys_sector_size,
    u32_t log_block_size, u32_t log_page_size);
s32_t fs_mount_specific(u32_t phys_addr, u32_t phys_size,
    u32_t phys_sector_size,
    u32_t log_block_size, u32_t log_page_size);
void fs_mount_dump(char *fname,
    u32_t addr_offset, u32_t phys_addr, u32_t phys_size,
        u32_t phys_sector_size,
        u32_t log_block_size, u32_t log_page_size);

void fs_store_dump(char *fname);
void fs_load_dump(char *fname);

void fs_set_addr_offset(u32_t offset);
int read_and_verify(char *name);
int read_and_verify_fd(spiffs_file fd, char *name);
void dump_page(spiffs *fs, spiffs_page_ix p);
void hexdump(u32_t addr, u32_t len);
char *make_test_fname(const char *name);
void clear_test_path();
void area_write(u32_t addr, u8_t *buf, u32_t size);
void area_set(u32_t addr, u8_t d, u32_t size);
void area_read(u32_t addr, u8_t *buf, u32_t size);
void dump_erase_counts(spiffs *fs);
void dump_flash_access_stats();
void set_flash_ops_log(int enable);
void clear_flash_ops_log();
u32_t get_flash_ops_log_read_bytes();
u32_t get_flash_ops_log_write_bytes();
void invoke_error_after_read_bytes(u32_t b, char once_only);
void invoke_error_after_write_bytes(u32_t b, char once_only);
void fs_set_validate_flashing(int i);

void memrand(u8_t *b, int len);
int test_create_file(char *name);
int test_create_and_write_file(char *name, int size, int chunk_size);
u32_t get_spiffs_file_crc_by_fd(spiffs_file fd);
u32_t get_spiffs_file_crc(char *name);
void _setup();
void _setup_test_only();
void _teardown();
u32_t tfile_get_size(tfile_size s);
int run_file_config(int cfg_count, tfile_conf* cfgs, int max_runs, int max_concurrent_files, int dbg);

void test_lock(spiffs *fs);
void test_unlock(spiffs *fs);

#endif /* TEST_SPIFFS_H_ */


text:
// ----------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// ----------------------------------------------------------------------------
/**
@typedef context
@description This object is attached to the express request object as the azureMobile property.
@property {module:queryjs/Query} query The parsed OData query if provided and the parseQuery middleware has been executed
@property {string|number} id The ID associated with the request if provided and the parseQuery middleware has been executed
@property {object} item The item being inserted or updated if provided and the parseItem middleware has been executed
@property {express.Request} req The current express {@link http://expressjs.com/4x/api.html#req request object}
@property {express.Response} res The current express {@link http://expressjs.com/4x/api.html#res response object}
@property {module:azure-mobile-apps/src/data} data The configured data provider
@property {NotificationHubService} [push] The {@link http://azure.github.io/azure-sdk-for-node/azure-sb/latest/NotificationHubService.html|Notification Hubs Service}, if configured
@property {configuration} configuration The azure mobile apps configuration object
@property {module:azure-mobile-apps/src/logger} logger The azure mobile apps logger
@property {function} tables A function that accepts a string table name and returns a table access object for the above provider
@property {module:azure-mobile-apps/src/express/tables/table} table The table definition object for the current table
@property {module:azure-mobile-apps/src/auth/user} user The authenticated user object if the authenticate middleware has been executed
@property {function} execute A function that executes the operation (read, insert, etc) against the table. Returns a promise with the results of the operation
*/


text:
#import <SimulatorKit/FoundationXPCProtocolProxyable-Protocol.h>

@protocol SimDisplayDamageRectangleDelegate <FoundationXPCProtocolProxyable>
- (void)didReceiveDamageRect:(struct CGRect)arg1;
@end


text:
package org.apache.fullmatix.mysql;

import org.apache.helix.participant.statemachine.StateModelFactory;

public class MasterSlaveTransitionHandlerFactory extends StateModelFactory<MasterSlaveTransitionHandler> {

  private Context _context;

  public MasterSlaveTransitionHandlerFactory(Context context) {
    _context = context;
  }

  @Override
  public MasterSlaveTransitionHandler createNewStateModel(String partition) {
    return new MasterSlaveTransitionHandler(_context, partition.split("_")[0],
        partition.toString());
  }

}


text:
"""First-person-shooter like movement control"""
from gettext import gettext as _
from OpenGLContext.move import direct
from OpenGLContext import arrays
from OpenGLContext.events import timer
from OpenGLContext.scenegraph import interpolators
import math

class Smooth( direct.Direct ):
    """Smooth movement using position interpolators

    Provides much smoother interaction than the direct base-class,
    produces smoothed interpolations between the current position/orientation
    and the target.
    """
    STEPDURATION = 0.05 # 1/20 of a second
    TURNANGLE = math.pi/64
    TURNDURATION = 0.05
    STEPDISTANCE = .25
    timer = None
    posInterpolator = None
    posTimer = orientTimer = None
    startOrient = None
    targetOrient = None

    def bind( self, context ):
        super( Smooth, self ).bind( context )
        self.posTimer = timer.Timer( duration = self.STEPDURATION )
        self.posTimer.register( context )
        self.orientTimer = timer.Timer( duration = self.TURNDURATION )
        self.orientTimer.register( context )
        self.posInterpolator = interpolators.PositionInterpolator( key = [0.0,1.0])
        self.orientInterpolator = interpolators.OrientationInterpolator( key = [0.0,1.0] )
        #context.addEventHandler(function=self.onFinished, node=self.timer, timetype='stop')
        self.posTimer.addEventHandler(
            timetype='fraction', function=self.onPositionFraction,
        )
        self.orientTimer.addEventHandler(
            timetype='fraction', function=self.onOrientFraction,
        )
    def restartPosTimer( self ):
        """Restart our timer to go to new location"""
        self.posTimer.stop()
        self.posTimer.start()
    def restartOrientTimer( self ):
        """Restart our timer to go to new location"""
        self.orientTimer.stop()
        self.orientTimer.start()
    def onPositionFraction( self, event ):
        """Process fractional update of our position"""
        fraction = (event.fraction() / 2.0) + .5
        x,y,z = self.posInterpolator.on_set_fraction( fraction )
        self.platform.position = arrays.array([x,y,z,0.0], 'f' )
    def onOrientFraction( self, event ):
        """Process fractional update of our position"""
        fraction = (event.fraction() / 2.0) + .5
        self.platform.quaternion = self.startOrient.slerp( self.targetOrient, fraction )
    def stepRelative( self, x=0,y=0,z=0 ):
        """Step given distance in view-relative coordinates"""
        self.posInterpolator.keyValue = [
            self.platform.position[:3],
            self.platform.relativePosition( x=x,y=y,z=z )[:3],
        ]
        self.restartPosTimer()
    def turn (self, deltaOrientation= (0,1,0,math.pi/4) ):
        turned = self.platform.relativeOrientation( deltaOrientation )
        self.startOrient = self.platform.quaternion # self.platform.quaternion.slerp( turned, .05 )
        self.targetOrient = turned
        self.restartOrientTimer()


text:
@class GHRepository, GHTree;

@interface GHSubmodule : GHResource
@property(nonatomic,strong)GHRepository *repository;
@property(nonatomic,readonly)GHTree *tree;
@property(nonatomic,strong)NSString *sha;
@property(nonatomic,strong)NSString *path;
@property(nonatomic,strong)NSString *name;
@property(nonatomic,readonly)NSString *shortenedSha;

- (id)initWithRepo:(GHRepository *)repo path:(NSString *)path sha:(NSString *)sha;
@end


text:
namespace CERental.Core.Domain
{
    public class EquipmentInRent : Entity
    {
        public int EquipmentId { get; set; }
        public int RentalId { get; set; }
        public int Days { get; set; }

        /* Navigational properties */
        public virtual Equipment Equipment { get; set; }
        public virtual Rental Rental { get; set; }
    }
}


text:
require "ruboty/paizaio/version"
require "ruboty/handlers/paizaio"

module Ruboty
  module Paizaio
    # Your code goes here...
  end
end


text:
"""Platform for Roth Touchline floor heating controller."""
import logging

from pytouchline import PyTouchline
import voluptuous as vol

from homeassistant.components.climate import PLATFORM_SCHEMA, ClimateEntity
from homeassistant.components.climate.const import (
    HVAC_MODE_HEAT,
    SUPPORT_PRESET_MODE,
    SUPPORT_TARGET_TEMPERATURE,
)
from homeassistant.const import ATTR_TEMPERATURE, CONF_HOST, TEMP_CELSIUS
import homeassistant.helpers.config_validation as cv

_LOGGER = logging.getLogger(__name__)

PRESET_MODES = {
    "Normal": {"mode": 0, "program": 0},
    "Night": {"mode": 1, "program": 0},
    "Holiday": {"mode": 2, "program": 0},
    "Pro 1": {"mode": 0, "program": 1},
    "Pro 2": {"mode": 0, "program": 2},
    "Pro 3": {"mode": 0, "program": 3},
}

TOUCHLINE_HA_PRESETS = {
    (settings["mode"], settings["program"]): preset
    for preset, settings in PRESET_MODES.items()
}

SUPPORT_FLAGS = SUPPORT_TARGET_TEMPERATURE | SUPPORT_PRESET_MODE

PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({vol.Required(CONF_HOST): cv.string})

def setup_platform(hass, config, add_entities, discovery_info=None):
    """Set up the Touchline devices."""

    host = config[CONF_HOST]
    py_touchline = PyTouchline()
    number_of_devices = int(py_touchline.get_number_of_devices(host))
    devices = []
    for device_id in range(0, number_of_devices):
        devices.append(Touchline(PyTouchline(device_id)))
    add_entities(devices, True)

class Touchline(ClimateEntity):
    """Representation of a Touchline device."""

    def __init__(self, touchline_thermostat):
        """Initialize the Touchline device."""
        self.unit = touchline_thermostat
        self._name = None
        self._current_temperature = None
        self._target_temperature = None
        self._current_operation_mode = None
        self._preset_mode = None

    @property
    def supported_features(self):
        """Return the list of supported features."""
        return SUPPORT_FLAGS

    def update(self):
        """Update thermostat attributes."""
        self.unit.update()
        self._name = self.unit.get_name()
        self._current_temperature = self.unit.get_current_temperature()
        self._target_temperature = self.unit.get_target_temperature()
        self._preset_mode = TOUCHLINE_HA_PRESETS.get(
            (self.unit.get_operation_mode(), self.unit.get_week_program())
        )

    @property
    def hvac_mode(self):
        """Return current HVAC mode.

        Need to be one of HVAC_MODE_*.
        """
        return HVAC_MODE_HEAT

    @property
    def hvac_modes(self):
        """Return list of possible operation modes."""
        return [HVAC_MODE_HEAT]

    @property
    def should_poll(self):
        """Return the polling state."""
        return True

    @property
    def name(self):
        """Return the name of the climate device."""
        return self._name

    @property
    def temperature_unit(self):
        """Return the unit of measurement."""
        return TEMP_CELSIUS

    @property
    def current_temperature(self):
        """Return the current temperature."""
        return self._current_temperature

    @property
    def target_temperature(self):
        """Return the temperature we try to reach."""
        return self._target_temperature

    @property
    def preset_mode(self):
        """Return the current preset mode."""
        return self._preset_mode

    @property
    def preset_modes(self):
        """Return available preset modes."""
        return list(PRESET_MODES)

    def set_preset_mode(self, preset_mode):
        """Set new target preset mode."""
        self.unit.set_operation_mode(PRESET_MODES[preset_mode]["mode"])
        self.unit.set_week_program(PRESET_MODES[preset_mode]["program"])

    def set_hvac_mode(self, hvac_mode):
        """Set new target hvac mode."""
        self._current_operation_mode = HVAC_MODE_HEAT

    def set_temperature(self, **kwargs):
        """Set new target temperature."""
        if kwargs.get(ATTR_TEMPERATURE) is not None:
            self._target_temperature = kwargs.get(ATTR_TEMPERATURE)
        self.unit.set_target_temperature(self._target_temperature)


text:
'use strict';
/**
* @author Iļja Gubins <ilja.gubin@gmail.com>
*/

/**
* Controller used for detail overview of specific server. Used with view serverDetails.html.
* Parameters are dependency injected.
* @function serversDetailsController
* @param $rootScope Used for global vars.
* @param $scope Used for data manipulation.
* @param $http Used for handling XHR requests.
* @param $routeParams Used for requesting URL parameters.
* @param $location Used for handing redirecting.
*/
function serversDetailsController($rootScope, $scope, $http, $routeParams, $location) {

    if ($rootScope.loggedIn) {

      //redirects back to main page if user comes to this url with serverId
      if (!$routeParams.serverId) {
        $location.path('/');
      }

      //host info
      $http.post(GlobalVars.api_url(), {
        jsonrpc: '2.0',
        id: $rootScope.auth_id,
        auth: $rootScope.auth,
        method: 'host.get',
        params: {
          selectInventory: true,
          selectItems: ['name','lastvalue',
            'units','itemid','lastclock','value_type','itemid'],
          output: 'extend',
          hostids: $routeParams.serverId,
          expandDescription: 1,
          expandData:1
        }
      }).success(function (hostData) {
        $scope.inventoryData = hostData.result[0].inventory;
        $scope.serverName = hostData.result[0].name;
        $scope.zabbix_url = GlobalVars.zabbix_url();
        $scope.hostId = $routeParams.serverId;
        if ($scope.itemsData = hostData.result[0].items) {
          for (var i = $scope.itemsData.length - 1; i >= 0; i--) {
            $scope.itemsData[i].lastclock = dateConverter($scope.itemsData[i].lastclock, "time");
          }
        }
        $('#filterInput').focus();
      });
    }
}


text:
package framework;

import java.lang.annotation.Annotation;
import java.lang.reflect.Constructor;
import java.lang.reflect.Executable;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.lang.reflect.Parameter;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.Supplier;
import java.util.stream.Stream;

import framework.annotation.Mapping;

/**
 * reflection object cache
 */
public class Reflector {
    /**
     * constructor cache{class, arguments hash : constructor}
     */
    static Map<Tuple<Class<?>, Integer>, Constructor<?>> constructors = new ConcurrentHashMap<>();

    /**
     * method cache{class, arguments hash : method}
     */
    static Map<Tuple<Class<?>, Integer>, Method> methods = new ConcurrentHashMap<>();

    /**
     * field cache{class : {field name : field}}
     */
    static Map<Tuple<Class<?>, Function<Field, String>>, Map<String, Field>> fields = new ConcurrentHashMap<>();

    /**
     * instance cache{class : instance}
     */
    static Map<Class<?>, Object> instances = new ConcurrentHashMap<>();

    /**
     * @param <T> target type
     * @param clazz target class
     * @param args constructor arguments
     * @return constructor
     */
    @SuppressWarnings("unchecked")
    public static <T> Optional<Constructor<T>> constructor(Class<T> clazz, Class<?>... args) {
        try {
            return Tool.of((Constructor<T>) constructors.computeIfAbsent(Tuple.of(clazz, Arrays.hashCode(args)), Try.f(pair -> {
                Constructor<?> result = pair.l.getDeclaredConstructor(args);
                result.setAccessible(true);
                return result;
            })));
        } catch (RuntimeException e) {
            return Optional.empty();
        }
    }

    /**
     * call no args constructor with cache
     *
     * @param <T> target type
     * @param clazz target class
     * @return instance
     */
    @SuppressWarnings("unchecked")
    public static <T> T constInstance(Class<T> clazz) {
        return (T) instances.computeIfAbsent(clazz, Reflector::instance);
    }

    /**
     * call no args constructor
     *
     * @param <T> target type
     * @param clazz target class
     * @return instance
     */
    public static <T> T instance(Class<T> clazz) {
        return constructor(clazz).map(Try.f(Constructor::newInstance)).orElse(null);
    }

    /**
     * call no args constructor
     *
     * @param <T> target type
     * @param clazz target class
     * @return instance
     */
    public static <T> T instance(String clazz) {
        return instance(Reflector.<T>clazz(clazz).<RuntimeException>orElseThrow(RuntimeException::new));
    }

    /**
     * @param <T> target type
     * @param clazz class
     * @return Class<T>
     */
    @SuppressWarnings("unchecked")
    public static <T> Optional<Class<T>> clazz(String clazz) {
        try {
            return Tool.of((Class<T>) Class.forName(clazz));
        } catch (ClassNotFoundException e) {
	    Log.config(e.toString());
            return Optional.empty();
        }
    }

    /**
     * @param clazz class
     * @param name field name
     * @return field
     */
    public static Optional<Field> field(Class<?> clazz, String name) {
        return Tool.of(fields(clazz).get(name));
    }

    /**
     * @param clazz class
     * @return Stream of field name and instance
     */
    public static Map<String, Field> fields(Class<?> clazz) {
    	return fields(clazz, Field::getName);
    }

    /**
     * @param clazz class
     * @param name field name
     * @return field
     */
    public static Optional<Field> mappingField(Class<?> clazz, String name) {
        return Tool.of(mappingFields(clazz).get(name));
    }

    /**
     * @param clazz class
     * @param getName Name getter
     * @return Stream of field name and instance
     */
    public static Map<String, Field> fields(Class<?> clazz, Function<Field, String> getName) {
	return fields.computeIfAbsent(Tuple.of(clazz, getName), pair -> {
	    Class<?> c = pair.l;
	    Map<String, Field> map = new LinkedHashMap<>();
	    while (c != Object.class && c != null) {
			Stream.of(c.getDeclaredFields()).filter(f -> !f.getName().contains("$")).map(f -> Tuple.of(getName.apply(f), f))
			.filter(t -> !map.containsKey(t.l)).peek(t -> t.r.setAccessible(true))
			.forEach(f -> map.put(f.l, f.r));
			c = c.getSuperclass();
	    }
	    return map;
	});
    }

    /**
     * @param clazz class
     * @return Stream of field name and instance
     */
    public static Map<String, Field> mappingFields(Class<?> clazz) {
    	return fields(clazz, Reflector::mappingFieldName);
    }

    /**
     * @param field target field
     * @return name
     */
    public static String mappingFieldName(Field field) {
		Mapping fieldAnnotation = field.getAnnotation(Mapping.class);
		Class<?> clazz = field.getDeclaringClass();
		return Tool.or(fieldAnnotation, () -> clazz.getAnnotation(Mapping.class)).map(mapping -> {
			return Reflector.<String>invoke(Reflector.constInstance(mapping.mapper()), "map",
					Tool.array(Class.class, Field.class, String.class), clazz, field,
					fieldAnnotation == null ? null : mapping.value());
		}).orElseGet(field::getName);
    }

    /**
     * @param clazz instance or class
     * @return table name
     */
    public static String mappingClassName(Object clazz) {
        Class<?> start = clazz instanceof Class ? (Class<?>) clazz : clazz.getClass();
        for (Class<?> c = start; c != Object.class; c = c.getSuperclass()) {
            Mapping mapping = c.getAnnotation(Mapping.class);
            if (mapping != null) {
                return Reflector.invoke(Reflector.constInstance(mapping.mapper()), "map",
                        Tool.array(Class.class, Field.class, String.class),
                        clazz, null, mapping.value());
            }
        }
        final String prefix = Optional.ofNullable(start.getEnclosingClass()).map(c -> c.getSimpleName() + "_").filter(s -> s.length() <= 2).orElse("");
        return prefix + start.getSimpleName();
    }

    /**
     * @param clazz class
     * @param name name
     * @param args argument types
     * @return method
     */
    public static Optional<Method> method(Class<?> clazz, String name, Class<?>... args) {
        return Tool.of(
                methods.computeIfAbsent(Tuple.of(clazz, Objects.hash(name, Arrays.hashCode(args))), Try.f(pair -> pair.l.getMethod(name, args), (e, pair) -> {
                    Method result = Try.s(() -> pair.l.getDeclaredMethod(name, args), ee -> null).get();
                    if (result != null) {
                        result.setAccessible(true);
                    }
                    return result;
                })));
    }

    /**
     * @param <T> Annotation type
     * @param enumValue Enum value
     * @param annotationClass annotation class
     * @return annotation
     */
    public static <T extends Annotation> Optional<T> annotation(Enum<?> enumValue, Class<T> annotationClass) {
        return field(enumValue.getDeclaringClass(), enumValue.name()).map(f -> f.getAnnotation(annotationClass));
    }

    /**
     * @param annotationClass annotation class
     * @return predicate
     */
    public static Predicate<Field> hasAnnotation(Class<? extends Annotation> annotationClass) {
        return field -> field.getAnnotation(annotationClass) != null;
    }

    /**
     * @param field Field
     * @param index Index
     * @return Generic type
     */
    public static Class<?> getGenericParameter(Field field, int index) {
        return (Class<?>) getGenericParameters(field)[index];
    }

    /**
     * @param field Field
     * @return Generic type
     */
    public static Type[] getGenericParameters(Field field) {
        Type type = field.getGenericType();
        return type instanceof ParameterizedType ? ((ParameterizedType) type).getActualTypeArguments() : Tool.array();
    }

    /**
     * @param <T> Return type
     * @param clazz Class
     * @param index Index
     * @return Generic type
     */
    @SuppressWarnings("unchecked")
    public static <T> Class<T> getGenericParameter(Class<?> clazz, int index) {
    	final Type[] types = getGenericParameters(clazz);
    	if(types.length <= 0) {
    		return null;
    	}
        return (Class<T>) types[index];
    }

    /**
     * @param <T> Return type
     * @param clazz Class
     * @return Generic type
     */
    public static <T> Type[] getGenericParameters(Class<?> clazz) {
        Type type = clazz.getGenericSuperclass();
        return type instanceof ParameterizedType ? ((ParameterizedType) type).getActualTypeArguments() : Tool.array();
    }

    /**
     * @param parameter Parameter
     * @return Generic parameters
     */
    public static Type[] getGenericParameters(Parameter parameter) {
        return Tool.of(parameter.getParameterizedType()).filter(i -> i instanceof ParameterizedType).map(i -> (ParameterizedType) i)
                .map(ParameterizedType::getActualTypeArguments).orElseGet(Tool::array);
    }

    /**
     * @param <T> Value type
     * @param annotation Target
     * @param methodName Method name
     * @return Default value
     */
    @SuppressWarnings("unchecked")
    public static <T> T getDefaultValue(Class<? extends Annotation> annotation, String methodName) {
        try {
            return (T) annotation.getMethod(methodName).getDefaultValue();
        } catch (NoSuchMethodException | SecurityException e) {
            return null;
        }
    }

    /**
     * @param value Value
     * @return True if modified value else false
     */
    public static boolean isModified(Object value) {
        if (value == null || value == Optional.empty()) {
            return false;
        }
        if (value instanceof Boolean) {
            return (boolean) value != false;
        }
        if (value instanceof Byte) {
            return (byte) value != (byte) 0;
        }
        if (value instanceof Short) {
            return (short) value != (short) 0;
        }
        if (value instanceof Integer) {
            return (int) value != 0;
        }
        if (value instanceof Long) {
            return (long) value != 0;
        }
        if (value instanceof Float) {
            return (float) value != 0;
        }
        if (value instanceof Double) {
            return (double) value != 0;
        }
        if (value instanceof Character) {
            return (char) value != (char) 0;
        }
        return true;
    }

    /**
     * @param <T> type
     * @param instance instance
     * @param name Property name
     * @param orElse call if not exists property
	 * @param accessField access field if not exists property
     * @return Property value
     */
    @SuppressWarnings("unchecked")
    public static <T> T getProperty(Object instance, String name, Supplier<T> orElse, boolean accessField) {
        if (instance != null) {
            Class<?> clazz = instance.getClass();
            Method m = Tool.string(name).flatMap(i -> method(clazz, "get" + Character.toUpperCase(i.charAt(0)) + i.substring(1)))
                    .orElseGet(() -> name.startsWith("is") ? method(clazz, name).orElse(null) : null);
            if (m != null) {
                try {
                    return (T) m.invoke(instance);
                } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
                    Log.warning(e, () -> "get property error");
                }
            } else if(accessField) {
            	return field(clazz, name).map(Try.f(field -> (T)field.get(instance), (e, field) -> {Log.warning(e, () -> "get property error");return null;})).orElseGet(orElse);
            }
        }
        return orElse.get();
    }

	/**
	 * @param instance instance
	 * @param type property type
	 * @param name property name
	 * @param value property value
	 * @param accessField access field if not exists property
	 */
	public static void setProperty(Object instance, Class<?> type, String name, Object value, boolean accessField) {
		if (instance != null) {
            Class<?> clazz = instance.getClass();
            Method m = Tool.string(name).flatMap(i -> method(clazz, "set" + Character.toUpperCase(i.charAt(0)) + i.substring(1), type)).orElse(null);
            if (m != null) {
                try {
                    m.invoke(instance, value);
                } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
                    Log.warning(e, () -> "set property error");
                }
            } else if(accessField) {
            	field(clazz, name).ifPresent(Try.c(field -> field.set(instance, value), (e, field) -> Log.warning(e, () -> "set property error")));
            }
		}
	}

    /**
     * @param <T> Return type
     * @param method Method
     * @param args Arguments
     * @return Return value
     */
    @SuppressWarnings("unchecked")
    public static <T> T invoke(Method method, Object... args) {
        return (T)Try.s(() -> method.invoke(Modifier.isStatic(method.getModifiers()) ? null : instance(method.getDeclaringClass()), args)).get();
    }

    /**
     * Static method invoke
     *
     * @param <T> Return type
     * @param methodFullName Full method name
     * @param argClasses Argument classes
     * @param args Arguments
     * @return Return value
     */
    @SuppressWarnings("unchecked")
    public static <T> T invoke(String methodFullName, Class<?>[] argClasses, Object... args) {
        int i = methodFullName.lastIndexOf('.');
        return i < 0 ? null
                : (T) clazz(methodFullName.substring(0, i)).flatMap(c -> method(c, methodFullName.substring(i + 1), argClasses))
                        .map(Try.f(m -> m.invoke(null, args))).orElse(null);
    }

    /**
     * @param            <T> Return type
     * @param instance   Instance
     * @param name       Method name
     * @param argClasses Argument classes
     * @param args       Arguments
     * @return Return value
     */
    @SuppressWarnings("unchecked")
    public static <T> T invoke(Object instance, String name, Class<?>[] argClasses, Object... args) {
        return (T) method(instance.getClass(), name, argClasses).map(Try.f(m -> m.invoke(instance, args))).orElse(null);
    }

    /**
     * @param clazz Target class
     * @param annotation Target annotation
     * @param value New value
     */
    @SuppressWarnings("unchecked")
    public static void chagneAnnotation(Class<?> clazz, Class<? extends Annotation> annotation, Annotation value) {
	Object data = invoke(clazz, "annotationData", Tool.array());
        field(data.getClass(), "annotations").map(Try.f(f -> Map.class.cast(f.get(data)))).ifPresent(map -> map.put(annotation, value));
    }

    /**
     * @param field Target field
     * @param annotation Target annotation
     * @param value New value
     */
    public static void chagneAnnotation(Field field, Class<? extends Annotation> annotation, Annotation value) {
        Reflector.<Map<Class<? extends Annotation>, Annotation>>invoke(field, "declaredAnnotations", Tool.array()).put(annotation, value);
    }

    /**
     * @param executable Target method or constructor
     * @param annotation Target annotation
     * @param value New value
     */
    @SuppressWarnings("unchecked")
    public static void chagneAnnotation(Executable executable, Class<? extends Annotation> annotation, Annotation value) {
        method(Executable.class, "declaredAnnotations").map(Try.f(m -> Map.class.cast(m.invoke(executable)))).ifPresent(map -> map.put(annotation, value));
    }

    /**
     * @param <T> target class type
     * @param <R> annotation class type
     * @param targetClass target class
     * @param annotationClass annotation class
     * @return annotation
     */
    public <T, R extends Annotation> Optional<R> annotation(Class<T> targetClass, Class<R> annotationClass) {
    	return Tool.or(targetClass.getAnnotation(annotationClass), () -> Stream.of(targetClass.getAnnotations()).map(i -> i.getClass().getAnnotation(annotationClass)).findFirst().orElse(null));
    }
}


text:
<?php
/**
 * The header for our theme.
 *
 * This is the template that displays all of the  section and everything up until

 *
 * @link https://developer.wordpress.org/themes/basics/template-files/#template-partials
 *
 * @package Beautiful_Reader
 */

?><!DOCTYPE html>
<html <?php language_attributes(); ?>>

<meta charset="<?php bloginfo( 'charset' ); ?>">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="profile" href="http://gmpg.org/xfn/11">
<link rel="pingback" href="<?php bloginfo( 'pingback_url' ); ?>">

<?php wp_head(); ?>

<body <?php body_class(); ?>>

	<?php esc_html_e( 'Skip to content', 'beautiful_reader' ); ?>

		<div class="site-branding
            <?php if ( get_header_image() ) : ?>
                site-branding--banner"
            style="background-image: url( <?php header_image(); ?> )
            <?php endif; // End header image check. ?>
        ">

            <?php beautiful_reader_the_site_logo(); ?>

            <button class="menu-toggle js-menu-toggle" aria-controls="primary-menu" aria-expanded="false"><?php esc_html_e( 'Menu', 'beautiful_reader' ); ?></button>
			<?php
			if ( is_front_page() && is_home() ) : ?>

<a href="<?php echo esc_url( home_url( '/' ) ); ?>" rel="home"><?php bloginfo( 'name' ); ?>

			<?php else : ?>

<a href="<?php echo esc_url( home_url( '/' ) ); ?>" rel="home"><?php bloginfo( 'name' ); ?>

			<?php
			endif;

			$description = get_bloginfo( 'description', 'display' );
			if ( $description || is_customize_preview() ) : ?>

<?php echo $description; /* WPCS: xss ok. */ ?>

			<?php
			endif; ?>

            <?php get_search_form(); ?>

			<?php wp_nav_menu( array( 'theme_location' => 'primary', 'menu_id' => 'primary-menu' ) ); ?>


text:
package com.github.cwilper.fcrepo.dto.core;

/**
 * The computed checksum of a {@link DatastreamVersion}'s content.
 *

 * A content digest has a type (MD5, SHA-1, etc.)
 * and a hex value (e.g. ea309a2eb146a4d8bdf8946c4df23c70).
 * This class does not validate or normalize these field values in any way.
 *
 * @see Working With DTO Classes
 */
public class ContentDigest extends FedoraDTO {

    private String type;
    private String hexValue;

    /**
     * Creates an instance.
     */
    public ContentDigest() {
    }

    /**
     * Creates an instance based on the current state of this one.
     *
     * @return a deep copy.
     */
    public ContentDigest copy() {
        return new ContentDigest().type(this.type).hexValue(this.hexValue);
    }

    /**
     * Gets the type of digest.
     *
     * @return the value, or null if undefined.
     */
    public String type() {
        return type;
    }

    /**
     * Sets the type of digest.
     *
     * @param type the new value, which will be string-normalized.
     * @return this instance.
     */
    public ContentDigest type(String type) {
        this.type = Util.normalize(type);
        return this;
    }

    /**
     * Gets the hex value.
     *
     * @return the value, or null if undefined.
     */
    public String hexValue() {
        return hexValue;
    }

    /**
     * Sets the hex value.
     *
     * @param hexValue the new value, which will be string-normalized.
     * @return this instance.
     */
    public ContentDigest hexValue(String hexValue) {
        this.hexValue = Util.normalize(hexValue);
        return this;
    }

    @Override
    Object[] getEqArray() {
        return new Object[] { type, hexValue };
    }

}


text:
define({
  "_widgetLabel": "Zoom-Schieberegler"
});


text:
package steps

import (
	"context"
	"errors"
	"fmt"
	"log"
	"strings"

	goflow "github.com/kamildrazkiewicz/go-flow"
)

// Step wraps a function and it's dependencies to perform concurrently
// optionally Retry can be specified for steps which need to be retried on error
type Step struct {
	Name      string
	DependsOn []string
	Do        func(context.Context) error
	Retry     int
}

type contextKeyType int

const (
	stepNameKey contextKeyType = iota
)

// Run takes a slice of Steps to be performed concurrently
func Run(ctx context.Context, steps []Step, logger *log.Logger) error {
	flow := goflow.New()
	for _, step := range steps {
		step := step
		dependsOn := step.DependsOn
		if len(dependsOn) == 0 {
			dependsOn = nil
		}
		flow.Add(step.Name, dependsOn, func(r map[string]interface{}) (interface{}, error) {
			if step.Do != nil {
				namedCtx := context.WithValue(ctx, stepNameKey, step.Name)
				l := ContextLogger(namedCtx, logger, "[Steps]")
				attempt := 1
				safelyDo := func() (err error) {
					defer func() {
						if r := recover(); r != nil {
							switch x := r.(type) {
							case string:
								err = errors.New(x)
							case error:
								err = x
							default:
								err = errors.New("Unknown panic")
							}
						}
					}()
					err = step.Do(namedCtx)
					return
				}
				for {
					err := safelyDo()
					if err != nil {
						if attempt <= step.Retry {
							l.Printf("Attempt %d retrying error: %s", attempt, err.Error())
							attempt++
							continue
						}
						l.Printf("Max retry %d reached giving up: %s", attempt, err.Error())
						return nil, fmt.Errorf("step %s failed: %v", step.Name, err)
					}
					return nil, nil
				}
			}
			return nil, nil
		})
	}
	_, err := flow.Do()
	return err
}

// ContextLogger can be used to get a logger prefixed with the current Step Name
func ContextLogger(ctx context.Context, logger *log.Logger, prefix string) *log.Logger {
	prefixes := []string{}
	if logger.Prefix() != "" {
		prefixes = append(prefixes, logger.Prefix())
	}
	if prefix != "" {
		prefixes = append(prefixes, prefix)
	}
	if v, ok := ctx.Value(stepNameKey).(string); ok {
		prefixes = append(prefixes, v)
	}
	if len(prefixes) > 0 {
		prefixes = append(prefixes, "")
	}

	return log.New(logger.Writer(), strings.Join(prefixes, " "), 0)
}


text:
{% extends "base.html" %}

{% block title %}Add Comment{% endblock %}
{% block content %}

    <form action="/comment/{{ suggestion }}/" method="post">
        {% csrf_token %}

Add Comment

        {{ form.errors }}
        {{ form.comment.label_tag }}
        {{ form.comment }}
        <input type="submit" class="button expanded" value="Add Comment" />
    </form>

{% endblock %}


text:
Prism
=====

Some helpers for configuring and serving `pyramid` apps.

## Stacked settings

`prism` provides a number of utilities for managing configuration
values, most notably the `compose_settings` decorator for use with
`paste.deploy` styles configuration.

This spelling (in it's most basic form):

 ```python
 from prism import config

 @config.compose_setttings
 def main(settings):
     ...
 ```

is rougly equivalent to:

 ```python
 # OLD WAY

 def main(global_config, settings):
     settings = global_config.copy()
     settings.update(settings)
     ...
 ```

The decorator also adds a plugin point for adding additional overrides
to the settings mapping.

For example, this plugin will roll up and flatten all the sections in
an inifile and add them to your settings.

 ```ini
 [app:main]
 use = egg:MyApp
 config.sources =
   prism.config.sources.ini_file

 config.ini_file = /path/to/some/config.ini
 ```


text:
package com.hortonworks.hdf.android.sitetosite.factory;

import com.hortonworks.hdf.android.sitetosite.client.QueuedSiteToSiteClientConfig;

public interface QueuedSiteToSiteClientConfigFactory<InputType> extends SiteToSiteClientConfigFactory<InputType> {
    QueuedSiteToSiteClientConfig create(InputType input) throws SiteToSiteClientConfigCreationException;
}


text:
namespace bowtie
{

uint64 hash_str(const char* str);

}


text:
function eps2pdf(source, dest, crop, append, gray, quality, gs_options)
%EPS2PDF  Convert an eps file to pdf format using ghostscript
%
% Examples:
%   eps2pdf source dest
%   eps2pdf(source, dest, crop)
%   eps2pdf(source, dest, crop, append)
%   eps2pdf(source, dest, crop, append, gray)
%   eps2pdf(source, dest, crop, append, gray, quality)
%   eps2pdf(source, dest, crop, append, gray, quality, gs_options)
%
% This function converts an eps file to pdf format. The output can be
% optionally cropped and also converted to grayscale. If the output pdf
% file already exists then the eps file can optionally be appended as a new
% page on the end of the eps file. The level of bitmap compression can also
% optionally be set.
%
% This function requires that you have ghostscript installed on your system.
% Ghostscript can be downloaded from: http://www.ghostscript.com
%
% Inputs:
%   source  - filename of the source eps file to convert. The filename is
%             assumed to already have the extension ".eps".
%   dest    - filename of the destination pdf file. The filename is assumed
%             to already have the extension ".pdf".
%   crop    - boolean indicating whether to crop the borders off the pdf.
%             Default: true.
%   append  - boolean indicating whether the eps should be appended to the
%             end of the pdf as a new page (if the pdf exists already).
%             Default: false.
%   gray    - boolean indicating whether the output pdf should be grayscale
%             or not. Default: false.
%   quality - scalar indicating the level of image bitmap quality to
%             output. A larger value gives a higher quality. quality > 100
%             gives lossless output. Default: ghostscript prepress default.
%   gs_options - optional ghostscript options (e.g.: '-dNoOutputFonts'). If
%                multiple options are needed, enclose in call array: {'-a','-b'}

% Copyright (C) Oliver Woodford 2009-2014, Yair Altman 2015-

% Suggestion of appending pdf files provided by Matt C at:
% http://www.mathworks.com/matlabcentral/fileexchange/23629

% Thank you Fabio Viola for pointing out compression artifacts, leading to the quality setting.
% Thank you Scott for pointing out the subsampling of very small images, which was fixed for lossless compression settings.

% 09/12/11: Pass font path to ghostscript
% 26/02/15: If temp dir is not writable, use the dest folder for temp destination files (Javier Paredes)
% 28/02/15: Enable users to specify optional ghostscript options (issue #36)
% 01/03/15: Upon GS error, retry without the -sFONTPATH= option (this might solve
%           some /findfont errors according to James Rankin, FEX Comment 23/01/15)
% 23/06/15: Added extra debug info in case of ghostscript error; code indentation
% 04/10/15: Suggest a workaround for issue #41 (missing font path; thanks Mariia Fedotenkova)
% 22/02/16: Bug fix from latest release of this file (workaround for issue #41)
% 20/03/17: Added informational message in case of GS croak (issue #186)
% 16/01/18: Improved appending of multiple EPS files into single PDF (issue #233; thanks @shartjen)
% 18/10/19: Workaround for GS 9.51+ .setpdfwrite removal problem (issue #285)
% 18/10/19: Warn when ignoring GS fontpath or quality options; clarified error messages
% 15/01/20: Added information about the GS/destination filepath in case of error (issue #294)
% 20/01/20: Attempted fix for issue #285: unsupported patch transparency in some Ghostscript versions
% 12/02/20: Improved fix for issue #285: add -dNOSAFER and -dALLOWPSTRANSPARENCY (thanks @linasstonys)
% 26/08/21: Added GS version to error message; fixed some problems with PDF append (issue #339)

    % Intialise the options string for ghostscript
    options = ['-q -dNOPAUSE -dBATCH -sDEVICE=pdfwrite -dPDFSETTINGS=/prepress -sOutputFile="' dest '"'];

    % Set crop option
    if nargin < 3 || crop
        options = [options ' -dEPSCrop'];
    end

    % Set the font path
    fp = font_path();
    if ~isempty(fp)
        options = [options ' -sFONTPATH="' fp '"'];
    end

    % Set the grayscale option
    if nargin > 4 && gray
        options = [options ' -sColorConversionStrategy=Gray -dProcessColorModel=/DeviceGray'];
    end

    % Set the bitmap quality
    qualityOptions = '';
    if nargin > 5 && ~isempty(quality)
        qualityOptions = ' -dAutoFilterColorImages=false -dAutoFilterGrayImages=false';
        if quality > 100
            qualityOptions = [qualityOptions ' -dColorImageFilter=/FlateEncode -dGrayImageFilter=/FlateEncode'];
            qualityOptions = [qualityOptions ' -c ".setpdfwrite << /ColorImageDownsampleThreshold 10 /GrayImageDownsampleThreshold 10 >> setdistillerparams"'];
        else
            qualityOptions = [qualityOptions ' -dColorImageFilter=/DCTEncode -dGrayImageFilter=/DCTEncode'];
            v = 1 + (quality < 80);
            quality = 1 - quality / 100;
            s = sprintf('<< /QFactor %.2f /Blend 1 /HSample [%d 1 1 %d] /VSample [%d 1 1 %d] >>', quality, v, v, v, v);
            qualityOptions = [qualityOptions ' -c ".setpdfwrite << /ColorImageDict ' s ' /GrayImageDict ' s ' >> setdistillerparams"'];
        end
        options = [options qualityOptions];
    end

    % Enable users to specify optional ghostscript options (issue #36)
    if nargin > 6 && ~isempty(gs_options)
        if iscell(gs_options)
            gs_options = sprintf(' %s',gs_options{:});
        elseif ~ischar(gs_options)
            error('gs_options input argument must be a string or cell-array of strings');
        else
            gs_options = [' ' gs_options];
        end
        options = [options gs_options];
    end

    % Check if the output file exists
    if nargin > 3 && append && exist(dest, 'file') == 2
        % Store the original filesize for later use below
        try
            file_info = dir(dest);
            orig_bytes = file_info.bytes;
        catch
            orig_bytes = [];
        end
        % File exists - append current figure to the end
        tmp_nam = [tempname '.pdf'];
        [fpath,fname,fext] = fileparts(tmp_nam);
        try
            % Ensure that the temp dir is writable (Javier Paredes 26/2/15)
            fid = fopen(tmp_nam,'w');
            fwrite(fid,1);
            fclose(fid);
            delete(tmp_nam);
        catch
            % Temp dir is not writable, so use the dest folder
            fpath = fileparts(dest);
            tmp_nam = fullfile(fpath,[fname fext]);
        end
        % Copy the original (dest) pdf file to temporary folder
        copyfile(dest, tmp_nam);
        % Produce an interim pdf of the source eps, rather than adding the eps directly (issue #233)
        % this will override the original (dest) pdf file
        orig_options = options;
        ghostscript([options ' -f "' source '"']);
        [~,fname] = fileparts(tempname);
        tmp_nam2 = fullfile(fpath,[fname fext]); % ensure using a writable folder (not necessarily tempdir)
        copyfile(dest, tmp_nam2);
        % Add the original pdf (tmp_nam) and interim pdf (dest=>tmp_nam2) as inputs to ghostscript
        %options = [options ' -f "' tmp_nam '" "' source '"'];  % append the source eps to dest pdf
        options = [options ' -f "' tmp_nam '" "' tmp_nam2 '"']; % append the interim pdf to dest pdf
        try
            % Convert to pdf using ghostscript
            [status, message] = ghostscript(options);
            % The output pdf should now be in dest

            % If the returned message is non-empty, a possible error may have
            % occured, so check the file size to ensure whether the file grew
            if ~isempty(message) && ~isempty(orig_bytes)
                file_info = dir(dest);
                new_bytes = file_info.bytes;
                if new_bytes < orig_bytes + 100
                    % Looks like nothing substantial (if anything) was appended to
                    % the original pdf, so try adding the eps file directly (issue #339)
                    options = [orig_options ' -f "' tmp_nam '" "' source '"'];  % append the source eps to dest pdf
                    [status, message] = ghostscript(options);
                end
            end

            % Delete the intermediate (temporary) files
            delete(tmp_nam);
            delete(tmp_nam2);
        catch me
            % Delete the intermediate files and rethrow the error
            delete(tmp_nam);
            delete(tmp_nam2);
            rethrow(me);
        end
    else
        % File doesn't exist or should be over-written
        % Add the source eps file as input to ghostscript
        options = [options ' -f "' source '"'];
        % Convert to pdf using ghostscript
        [status, message] = ghostscript(options);
    end

    % Check for error
    if status
        % Catch and correct undefined .setopacityalpha errors (issue #285)
        % (see explanation inside print2eps.m)
        if ~isempty(regexpi(message,'undefined in .setopacityalpha'))
            % First try with -dNOSAFER and -dALLOWPSTRANSPARENCY  (thanks @linasstonys)
            new_options = [options ' -dNOSAFER -dALLOWPSTRANSPARENCY'];
            [status, message] = ghostscript(new_options);
            if ~status  % hurray! (no error)
                return
            elseif isempty(regexpi(message,'undefined in .setopacityalpha'))  % still some other error
                options = new_options;
            else  % we still get a .setopacityalpha error
                % Remove the transparency and retry
                fstrm = read_write_entire_textfile(source);
                fstrm = regexprep(fstrm, '0?\.\d+ .setopacityalpha \w+\n', '');
                read_write_entire_textfile(source, fstrm);
                [status, message] = ghostscript(options);
                if ~status % hurray! (no error)
                    % Alert the user that transparency is not supported
                    warning('export_fig:GS:quality','Export_fig Face/Edge alpha transparancy is ignored - not supported by your Ghostscript version')
                    return
                end
            end
        end

        % Retry without the -sFONTPATH= option (this might solve some GS
        % /findfont errors according to James Rankin, FEX Comment 23/01/15)
        orig_options = options;
        if ~isempty(fp)
            options = regexprep(options, ' -sFONTPATH=[^ ]+ ',' ');
            [status, message] = ghostscript(options);
            if ~status % hurray! (no error)
                warning('export_fig:GS:fontpath','Export_fig font option is ignored - not supported by your Ghostscript version')
                return
            end
        end

        % Retry without quality options (may solve problems with GS 9.51+, issue #285)
        if ~isempty(qualityOptions)
            options = strrep(orig_options, qualityOptions, '');
            [status, message] = ghostscript(options);
            if ~status % hurray! (no error)
                warning('export_fig:GS:quality','Export_fig quality option is ignored - not supported by your Ghostscript version')
                return
            end
        end

        % Report error
        if isempty(message)
            error(['Unable to generate pdf. Ensure that the destination folder (' fileparts(dest) ') is writable.']);
        elseif ~isempty(strfind(message,'/typecheck in /findfont')) %#ok<STREMP>
            % Suggest a workaround for issue #41 (missing font path)
            font_name = strtrim(regexprep(message,'.*Operand stack:\s*(.*)\s*Execution.*','$1'));
            fprintf(2, 'Ghostscript error: could not find the following font(s): %s\n', font_name);
            %fpath = fileparts(mfilename('fullpath'));
            %gs_fonts_file = fullfile(fpath, '.ignore', 'gs_font_path.txt');
            [unused, gs_fonts_file] = user_string('gs_font_path'); %#ok<ASGLU>
            fprintf(2, '  try to add the font''s folder to your %s file\n\n', gs_fonts_file);
            error('export_fig error');
        else
            gs_options = strtrim(gs_options);
            fprintf(2, '\nGhostscript error: ');
            msg = regexprep(message, '^Error: /([^\n]+).*', '$1');
            if ~isempty(msg) && ~strcmp(msg,message)
                fprintf(2,'%s',msg);
            end
            fprintf(2, '\n * perhaps %s is open by another application\n', dest);
            try gs_version = str2num(evalc('ghostscript(''--version'');')); catch, gs_version = ''; end %#ok<ST2NM>
            if ~isempty(gs_version), gs_version = [' ' num2str(gs_version)]; end
            if ~isempty(gs_options)
                fprintf(2, ' * or maybe your Ghostscript version%s does not accept the extra "%s" option(s) that you requested\n', gs_version, gs_options);
            end
            fprintf(2, ' * or maybe you have another gs executable in your system''s path\n\n');
            fprintf(2, 'Ghostscript path: %s\n', user_string('ghostscript'));
            fprintf(2, 'Ghostscript options: %s\n\n', orig_options);
            error(message);
        end
    end
end

% Function to return (and create, where necessary) the font path
function fp = font_path()
    fp = user_string('gs_font_path');
    if ~isempty(fp)
        return
    end
    % Create the path
    % Start with the default path
    fp = getenv('GS_FONTPATH');
    % Add on the typical directories for a given OS
    if ispc
        if ~isempty(fp)
            fp = [fp ';'];
        end
        fp = [fp getenv('WINDIR') filesep 'Fonts'];
    else
        if ~isempty(fp)
            fp = [fp ':'];
        end
        fp = [fp '/usr/share/fonts:/usr/local/share/fonts:/usr/share/fonts/X11:/usr/local/share/fonts/X11:/usr/share/fonts/truetype:/usr/local/share/fonts/truetype'];
    end
    user_string('gs_font_path', fp);
end


text:
More than a manual, a small list of reminders for me. If you find it useful, good for you.

HOWTOs

Migrate a folder with its history to another repository

I had to do that because I put everything (C#, python, microcontroller, eagle,...) files in one repository which obviously became too big and kind a messy. So I decided to move out some chuncks of it outside to a dedicated smaller repo (ie: eagle files in May2020). This is how I did it.

**Foreword**: I based this on [[https://medium.com/@ayushya/move-directory-from-one-repository-to-another-preserving-git-history-d210fa049d4b|that tutorial]] that I followed but it wasn't clear enough to me so let me re-explain it my way, but credits go to the author of the original one.

Theory

Basically you add to the //target-repo// a reference to the //source-repo//, merge the histories, remove the reference to the //source-repo// and done. But there's a few steps to that.

You need to remove everything you don't want from //source-repo// before copying to //target-repo//. Obvious, because otherwise the whole hisotry of everything would be duplicated, a waste of space and not your goal (you want 1 folder to move).

#Say you want to move folder source-repo/FOLDER_TO_KEEP to target-repo/NEW_FOLDER with its whole history and content.

#create a dummy work folder
mkdir temp-repo
cd temp-repo

#checkout source-repo there
git clone [source-repo-url]

#remove immediately the link to the origin to avoid messing up the original one
cd source-repo
git remote rm origin

#there, now even if you mess-up your changes won't be pushed to github

#now a command you don't often type: it will delete everything in your repo EXCEPT the FOLDER_TO_KEEP
# and !!surprise!!, it will move the content of FOLDER_TO_KEEP to the root of the repo
git filter-branch --subdirectory-filter [FOLDER_TO_KEEP] -- --all

#pruning & cleaning violently
git reset --hard
git gc --aggressive
git prune
git clean -fd

#now your repo is clean as a whistle of any record of information except the FOLDER_TO_KEEP part BUT now the files are at the root of the repo

[OPTIONAL]

#maybe you want the files in a subfolder of your repo, not at the root? so let's do it
mkdir NEW_FOLDER
mv -R * NEW_FOLDER/

#make sure everything is committed
git add -A .
git commit

[/OPTIONAL]

#now go to your target-repo
cd ../target-repo

#plug a reference to your modified copy of the source-repo. Not the real source-repo, the one you just cleaned up in temp-repo/ folder
#"dummy-name" is just to give a label to the reference. anything is fine, you'll delete it in 2 minutes. I will go with "dummy-name"
git remote add dummy-name [path-to-temp-repo-folder]

#now the magical mariage of the 2 repos history
git pull dummy-name master --allow-unrelated-histories

#remove that dummy reference
git remote rm dummy-name

#and now the local target-repo has gained all the files and history of source-repo concerning FOLDER_TO_KEEP, time to push to github
git push

#go grab your preferred drink, you earned it


text:
pub( crate ) mod private
{
  use crate::*;

  /// ChangerInterface of brush stroke.
  #[ allow( dead_code ) ]
  #[ derive( Debug, Clone ) ]
  pub struct DrawingChangeNew
  {
    id : Id,
  }

  impl DrawingChangeNew
  {
    /// Constructor.
    pub fn new( id : Id ) -> Self
    {
      Self{ id }
    }
  }

  impl ChangeInterface for DrawingChangeNew
  {
  }

}

crate::mod_interface!
{
  exposed use DrawingChangeNew;
}


text:
package flex.tools.debugger.cli;

/**
 * While attempting to resolve a function name or filename, no match
 * was found.  For example, this is thrown if the user enters
 * "break foo.mxml:12" but there is no file called "foo.mxml".
 */
public class NoMatchException extends Exception
{
    private static final long serialVersionUID = 721945420519126096L;

    public NoMatchException() {}
	public NoMatchException(String s) { super(s); }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project>
  <modelVersion>4.0.0</modelVersion>
  <artifactId>xtee-client-lrv6</artifactId>
  <name>lrv6 client services</name>

  <parent>
    <groupId>com.nortal.jroad</groupId>
    <artifactId>xtee-client-service</artifactId>
    <version>4.2.11</version>
  </parent>

  <properties>
    <package>lrv6</package>
  </properties>
</project>


text:
require File.expand_path('../../../spec_helper', __FILE__)
require File.expand_path('../fixtures/classes', __FILE__)

if System.get_property('platform') != 'APPLE'
describe "IO#stat" do
  before :each do
    @io = IO.popen 'cat', "r+"
  end

  after :each do
    @io.close unless @io.closed?
  end

  #it "raises IOError on closed stream" do
  #  lambda { IOSpecs.closed_io.stat }.should raise_error(IOError)
  #end

  #it "returns a File::Stat object for the stream" do
  #  STDOUT.stat.should be_an_instance_of(File::Stat)
  #end

  it "can stat pipes" do
    @io.stat.should be_an_instance_of(File::Stat)
  end
end
end


text:
<?php

defined('JPATH_PLATFORM') or die;

use Joomla\Registry\Registry;

/**
 * Form Rule class for the Joomla Platform.
 *
 * @since  11.1
 */
class JFormRuleUsername extends JFormRule
{
	/**
	 * Method to test the username for uniqueness.
	 *
	 * @param   SimpleXMLElement  $element  The SimpleXMLElement object representing the `<field>` tag for the form field object.
	 * @param   mixed             $value    The form field value to validate.
	 * @param   string            $group    The field name group control value. This acts as an array container for the field.
	 *                                      For example if the field has name="foo" and the group value is set to "bar" then the
	 *                                      full field name would end up being "bar[foo]".
	 * @param   Registry          $input    An optional Registry object with the entire data set to validate against the entire form.
	 * @param   JForm             $form     The form object for which the field is being tested.
	 *
	 * @return  boolean  True if the value is valid, false otherwise.
	 *
	 * @since   11.1
	 */
	public function test(SimpleXMLElement $element, $value, $group = null, Registry $input = null, JForm $form = null)
	{
		// Get the database object and a new query object.
		$db = JFactory::getDbo();
		$query = $db->getQuery(true);

		// Build the query.
		$query->select('COUNT(*)')
			->from('#__users')
			->where('username = ' . $db->quote($value));

		// Get the extra field check attribute.
		$userId = ($form instanceof JForm) ? $form->getValue('id') : '';
		$query->where($db->quoteName('id') . ' <> ' . (int) $userId);

		// Set and query the database.
		$db->setQuery($query);
		$duplicate = (bool) $db->loadResult();

		if ($duplicate)
		{
			return false;
		}

		return true;
	}
}


text:
name             "Entity Code Generator"
maintainer       "MiYABiS"
license          "Apache 2.0"
description      "Installs/Configures the Entity Code Generator"
long_description IO.read(File.join(File.dirname(__FILE__), 'README.md'))
version          "1.0.0"
supports         "windows"

depends          "windows", ">= 1.2.2"


text:
package jp.ikedam.jenkins.plugins.redirect404.testutils;

import hudson.model.FreeStyleProject;

import java.io.IOException;

import org.jvnet.hudson.test.JenkinsRule;

/**
 *
 */
public class Redirect404JenkinsRule extends JenkinsRule {
    @Override
    public FreeStyleProject createFreeStyleProject() throws IOException {
        return super.createFreeStyleProject();
    }

    public WebClient createWebClientForFilterTest() {
        WebClient wc = super.createWebClient();
        wc.setPrintContentOnFailingStatusCode(false);
        wc.setThrowExceptionOnFailingStatusCode(false);
        return wc;
    }
}


text:
cask 'unetbootin' do
  version '677'
  sha256 '2f232c59e0a1d627206df3618e0b71ff0227b7ec985c679f1cc5e6bd4ea1cd5b'

  # github.com/unetbootin/unetbootin was verified as official when first introduced to the cask
  url "https://github.com/unetbootin/unetbootin/releases/download/#{version}/unetbootin-mac-#{version}.dmg"
  appcast 'https://github.com/unetbootin/unetbootin/releases.atom'
  name 'UNetbootin'
  homepage 'https://unetbootin.github.io/'

  app 'unetbootin.app'

  zap trash: '~/Library/Application Support/com.apple.sharedfilelist/com.apple.LSSharedFileList.ApplicationRecentDocuments/com.yourcompany.unetbootin.sfl*'
end


text:
using namespace tool;

// to-do: use QDir instead of c++ library
int tool::getvtkfiles (string dir, vector<tool::TractData> &files){
   DIR *dp;
   struct dirent *dirp;
   if((dp  = opendir(dir.c_str())) == NULL) {
         //cout << "Error(" << errno << ") opening " << dir << endl;
         return errno;
   }

   while((dirp = readdir(dp)) != NULL){

       // select files with vtk prefix
       string filepath = string(dirp->d_name);
       size_t found = filepath.find_last_of(".");
       string prefix = filepath.substr(found+1);
       if (prefix == "vtk"){
           size_t found_name = filepath.find_last_of("/");
           string filename = filepath.substr(found_name+1);
           // to-do: subject ID is trivial
           tool::TractData newTract = {
               QString::fromStdString(filename),  // file name
               QString("UniTract")  //subject ID
           };
           files.push_back(newTract);
       }

   }
   closedir(dp);
   return 0;

}

bool tool::checkNewLine(string &s){
    string::iterator i = s.end()-1;
    if(*i == '\n'){
        s.erase(i,i+1);
        return true;
    }else
        return false;
}

bool tool::checkDirExist(string path){
    struct stat info;
    if(stat(path.c_str(),&info)!=0)
        return false;
    else if(info.st_mode & S_IFDIR)
        return true;
    else
        return false;
}

string tool::syscall(const char* cmd){
    FILE* pipe = popen(cmd,"r");
    if(!pipe) return NULL;
    char buffer[256];
    string result = "";
    while(!feof(pipe)){
        if(fgets(buffer,256,pipe)){
            result += buffer;
        }
    }
    pclose(pipe);
    return result;
}

void tool::tokenize(char* str, const char* delimiter, vector<string> &results){
    results.clear();
    char* tok = strtok(str,delimiter);
    while(tok!= NULL){
        results.push_back(string(tok));
        tok = strtok(NULL,delimiter);
    }
}

void tool::parseMapContent(QString filename, map<string,TractData> &data, string header1, string header2){

    char path[1024];
    char sid[1024];
    csvparser in(filename);
    in.read(header1,header2);
    while(in.read_row(path,sid)){
        tool::TractData newTract = {
            QString::fromStdString(path),
            QString::fromStdString(sid)
        };
        auto element = std::make_pair(sid,newTract);
        data.insert(element);
    }

}

bool tool::checkExecutable(string path){
    QFileInfo info(QString::fromStdString(path));
    if(!info.isDir() && info.isExecutable())
        return true;
    return false;
}

bool tool::checkExecutable(char* path){
    std::string str(path);
    checkExecutable(str);
}

// generic parsing of csv files
vector<vector<string>> tool::parseCSV(string dir, vector<string> &attrs){
    csvparser scanner(QString::fromStdString(dir));
    attrs.clear();
    // header line
    char line[10000];
    scanner.next_line(line,sizeof(line));
    tokenize(line,",",attrs);
    vector<vector<string>> results;
    // content
    // to-do: check for csv consistency
    while (scanner.next_line(line,sizeof(line))){
        vector<string> new_arr;
        tokenize(line,",",new_arr);
        results.push_back(new_arr);
    }
    scanner.close();
    return results;
}


text:
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion

#if NETFX_CORE
using System;
using Newtonsoft.Json.Converters;
#if !NETFX_CORE
using NUnit.Framework;
#else
using Microsoft.VisualStudio.TestPlatform.UnitTestFramework;
using TestFixture = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestClassAttribute;
using Test = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestMethodAttribute;
#endif
using Windows.Data.Json;
using System.IO;
using System.Diagnostics;
using Newtonsoft.Json.Linq;
using System.Collections.Generic;
using System.Linq;

namespace Newtonsoft.Json.Tests.Converters
{
  [TestFixture]
  public class JsonValueConverterTests : TestFixtureBase
  {
    public class Computer
    {
      public string Cpu { get; set; }
      public List<string> Drives { get; set; }
    }

    [Test]
    public void WriteJson()
    {
      JsonObject o = JsonObject.Parse(@"{
  ""CPU"": ""Intel"",
  ""Drives"": [
    ""DVD read/writer"",
    ""500 gigabyte hard drive""
  ]
}");

      StringWriter sw = new StringWriter();
      JsonTextWriter writer = new JsonTextWriter(sw);

      JsonValueConverter converter = new JsonValueConverter();
      converter.WriteJson(writer, o, null);

      string json = sw.ToString();

      Assert.AreEqual(@"{""Drives"":[""DVD read/writer"",""500 gigabyte hard drive""],""CPU"":""Intel""}", json);
    }

    [Test]
    public void ReadJson()
    {
      string json = @"{
  ""CPU"": ""Intel"",
  ""Drives"": [
    ""DVD read/writer"",
    ""500 gigabyte hard drive""
  ]
}";

      JsonTextReader writer = new JsonTextReader(new StringReader(json));

      JsonValueConverter converter = new JsonValueConverter();
      JsonObject o = (JsonObject)converter.ReadJson(writer, typeof(JsonObject), null, null);

      Assert.AreEqual(2, o.Count);
      Assert.AreEqual("Intel", o.GetNamedString("CPU"));
      Assert.AreEqual("DVD read/writer", o.GetNamedArray("Drives")[0].GetString());
      Assert.AreEqual("500 gigabyte hard drive", o.GetNamedArray("Drives")[1].GetString());
    }

    [Test]
    public void ReadJsonComments()
    {
      string json = @"{/*comment!*/
  ""CPU"": ""Intel"",/*comment!*/
  ""Drives"": [/*comment!*/
    ""DVD read/writer"",
    /*comment!*/""500 gigabyte hard drive""
  ]/*comment!*/
}";

      JsonTextReader writer = new JsonTextReader(new StringReader(json));

      JsonValueConverter converter = new JsonValueConverter();
      JsonObject o = (JsonObject)converter.ReadJson(writer, typeof(JsonObject), null, null);

      Assert.AreEqual(2, o.Count);
      Assert.AreEqual("Intel", o.GetNamedString("CPU"));
      Assert.AreEqual("DVD read/writer", o.GetNamedArray("Drives")[0].GetString());
      Assert.AreEqual("500 gigabyte hard drive", o.GetNamedArray("Drives")[1].GetString());
    }

    [Test]
    public void ReadJsonNullValue()
    {
      string json = "null";

      JsonTextReader writer = new JsonTextReader(new StringReader(json));

      JsonValueConverter converter = new JsonValueConverter();
      JsonValue v = (JsonValue)converter.ReadJson(writer, typeof(JsonValue), null, null);

      Assert.AreEqual(JsonValueType.Null, v.ValueType);
    }

    [Test]
    public void ReadJsonUnsupportedValue()
    {
      string json = "undefined";

      JsonTextReader writer = new JsonTextReader(new StringReader(json));

      JsonValueConverter converter = new JsonValueConverter();

      ExceptionAssert.Throws<JsonException>("Unexpected or unsupported token: Undefined. Path '', line 1, position 9.",
      () =>
      {
        converter.ReadJson(writer, typeof(JsonValue), null, null);
      });
    }

    [Test]
    public void ReadJsonUnexpectedEndInArray()
    {
      string json = "[";

      JsonTextReader writer = new JsonTextReader(new StringReader(json));

      JsonValueConverter converter = new JsonValueConverter();

      ExceptionAssert.Throws<JsonException>("Unexpected end. Path '', line 1, position 1.",
      () =>
      {
        converter.ReadJson(writer, typeof(JsonValue), null, null);
      });
    }

    [Test]
    public void ReadJsonUnexpectedEndAfterComment()
    {
      string json = "[/*comment!*/";

      JsonTextReader writer = new JsonTextReader(new StringReader(json));

      JsonValueConverter converter = new JsonValueConverter();

      ExceptionAssert.Throws<JsonException>("Unexpected end. Path '', line 1, position 13.",
      () =>
      {
        converter.ReadJson(writer, typeof(JsonValue), null, null);
      });
    }

    [Test]
    public void ReadJsonUnexpectedEndInObject()
    {
      string json = "{'hi':";

      JsonTextReader writer = new JsonTextReader(new StringReader(json));

      JsonValueConverter converter = new JsonValueConverter();

      ExceptionAssert.Throws<JsonException>("Unexpected end. Path 'hi', line 1, position 6.",
      () =>
      {
        converter.ReadJson(writer, typeof(JsonValue), null, null);
      });
    }

    [Test]
    public void ReadJsonBadJsonType()
    {
      string json = "null";

      JsonTextReader writer = new JsonTextReader(new StringReader(json));

      JsonValueConverter converter = new JsonValueConverter();

      ExceptionAssert.Throws<JsonException>("Could not convert 'Windows.Data.Json.JsonValue' to 'Windows.Data.Json.JsonObject'. Path '', line 1, position 4.",
      () =>
      {
        converter.ReadJson(writer, typeof(JsonObject), null, null);
      });
    }

    [Test]
    public void JsonConvertDeserialize()
    {
      string json = @"[
  ""DVD read/writer"",
  ""500 gigabyte hard drive""
]";

      JsonArray a = JsonConvert.DeserializeObject<JsonArray>(json);

      Assert.AreEqual(2, a.Count);
      Assert.AreEqual("DVD read/writer", a[0].GetString());
      Assert.AreEqual("500 gigabyte hard drive", a[1].GetString());
    }

    [Test]
    public void JsonConvertSerialize()
    {
      JsonArray a = JsonArray.Parse(@"[
  ""DVD read/writer"",
  ""500 gigabyte hard drive""
]");

      string json = JsonConvert.SerializeObject(a, Formatting.Indented);

      Assert.AreEqual(@"[
  ""DVD read/writer"",
  ""500 gigabyte hard drive""
]", json);
    }

    [Test]
    public void SerializeDouble()
    {
      JsonObject o = new JsonObject();
      o["zero"] = JsonValue.CreateNumberValue(0);
      o["int"] = JsonValue.CreateNumberValue(1);
      o["smallfraction"] = JsonValue.CreateNumberValue(3.0000000000000009);
      o["double"] = JsonValue.CreateNumberValue(1.1);
      o["probablyint"] = JsonValue.CreateNumberValue(1.0);
      o["Epsilon"] = JsonValue.CreateNumberValue(double.Epsilon);
      o["MinValue"] = JsonValue.CreateNumberValue(double.MinValue);
      o["MaxValue"] = JsonValue.CreateNumberValue(double.MaxValue);
      o["NaN"] = JsonValue.CreateNumberValue(double.NaN);
      o["NegativeInfinity"] = JsonValue.CreateNumberValue(double.NegativeInfinity);
      o["PositiveInfinity"] = JsonValue.CreateNumberValue(double.PositiveInfinity);

      string json = JsonConvert.SerializeObject(o, Formatting.Indented);

      Assert.AreEqual(@"{
  ""PositiveInfinity"": ""Infinity"",
  ""NegativeInfinity"": ""-Infinity"",
  ""MinValue"": -1.7976931348623157E+308,
  ""double"": 1.1,
  ""int"": 1,
  ""zero"": 0,
  ""Epsilon"": 4.94065645841247E-324,
  ""MaxValue"": 1.7976931348623157E+308,
  ""NaN"": ""NaN"",
  ""smallfraction"": 3.0000000000000009,
  ""probablyint"": 1
}", json);
    }

    [Test]
    public void DeserializePerformance()
    {
      string json = @"{
  ""CPU"": ""Intel"",
  ""Drives"": [
    ""DVD read/writer"",
    ""500 gigabyte hard drive""
  ]
}";

      Stopwatch timer = new Stopwatch();
      timer.Start();
      for (int i = 0; i < 100000; i++)
      {
        JsonObject o = JsonObject.Parse(json);
      }
      timer.Stop();

      string winrt = timer.Elapsed.TotalSeconds.ToString();

      timer = new Stopwatch();
      timer.Start();
      for (int i = 0; i < 100000; i++)
      {
        JObject o = JObject.Parse(json);
      }
      timer.Stop();

      string linq = timer.Elapsed.TotalSeconds.ToString();

      // warm up
      JsonConvert.DeserializeObject<Computer>(json);

      timer = new Stopwatch();
      timer.Start();
      for (int i = 0; i < 100000; i++)
      {
        Computer o = JsonConvert.DeserializeObject<Computer>(json);
      }
      timer.Stop();

      string jsonnet = timer.Elapsed.TotalSeconds.ToString();

      throw new Exception(string.Format("winrt: {0}, jsonnet: {1}, jsonnet linq: {2}", winrt, jsonnet, linq));
    }

    [Test]
    public void SerializePerformance()
    {
      string json = @"{
  ""CPU"": ""Intel"",
  ""Drives"": [
    ""DVD read/writer"",
    ""500 gigabyte hard drive""
  ]
}";

      JsonObject o = JsonObject.Parse(json);
      JObject o1 = JObject.Parse(json);
      Computer o2 = JsonConvert.DeserializeObject<Computer>(json);

      Stopwatch timer = new Stopwatch();
      timer.Start();
      for (int i = 0; i < 100000; i++)
      {
        o.Stringify();
      }
      timer.Stop();

      string winrt = timer.Elapsed.TotalSeconds.ToString();

      timer.Start();
      for (int i = 0; i < 100000; i++)
      {
        o1.ToString(Formatting.None);
      }
      timer.Stop();

      string linq = timer.Elapsed.TotalSeconds.ToString();

      timer = new Stopwatch();
      timer.Start();
      for (int i = 0; i < 100000; i++)
      {
        JsonConvert.SerializeObject(o);
      }
      timer.Stop();

      string jsonnet = timer.Elapsed.TotalSeconds.ToString();

      throw new Exception(string.Format("winrt: {0}, jsonnet: {1}, jsonnet linq: {2}", winrt, jsonnet, linq));
    }

    [Test]
    public void ParseJson()
    {
      string json = @"{
        ""channel"": {
          ""title"": ""James Newton-King"",
          ""link"": ""http://james.newtonking.com"",
          ""description"": ""James Newton-King's blog."",
          ""item"": [
            {
              ""title"": ""Json.NET 1.3 + New license + Now on CodePlex"",
              ""description"": ""Annoucing the release of Json.NET 1.3, the MIT license and the source being available on CodePlex"",
              ""link"": ""http://james.newtonking.com/projects/json-net.aspx"",
              ""category"": [
                ""Json.NET"",
                ""CodePlex""
              ]
            }
          ]
        }
      }";

      // Windows.Data.Json
      // -----------------
      JsonObject jsonObject = JsonObject.Parse(json);
      string itemTitle1 = jsonObject["channel"].GetObject()["item"].GetArray()[0].GetObject()["title"].GetString();

      // LINQ to JSON
      // ------------
      JObject jObject = JObject.Parse(json);
      string itemTitle2 = (string)jObject["channel"]["item"][0]["title"];
    }

    [Test]
    public void CreateJson()
    {
      // Windows.Data.Json
      // -----------------
      JsonObject jsonObject = new JsonObject
        {
          {"CPU", JsonValue.CreateStringValue("Intel")},
          {"Drives", new JsonArray {
              JsonValue.CreateStringValue("DVD read/writer"),
              JsonValue.CreateStringValue("500 gigabyte hard drive")
            }
          }
        };
      string json1 = jsonObject.Stringify();

      // LINQ to JSON
      // ------------
      JObject jObject = new JObject
        {
          {"CPU", "Intel"},
          {"Drives", new JArray {
              "DVD read/writer",
              "500 gigabyte hard drive"
            }
          }
        };
      string json2 = jObject.ToString();
    }

    [Test]
    public void Converting()
    {
      JsonObject jsonObject = new JsonObject
        {
          {"CPU", JsonValue.CreateStringValue("Intel")},
          {"Drives", new JsonArray {
              JsonValue.CreateStringValue("DVD read/writer"),
              JsonValue.CreateStringValue("500 gigabyte hard drive")
            }
          }
        };

      // convert Windows.Data.Json to LINQ to JSON
      JObject o = JObject.FromObject(jsonObject);

      // convert LINQ to JSON to Windows.Data.Json
      JArray a = (JArray)o["Drives"];
      JsonArray jsonArray = a.ToObject<JsonArray>();
    }
  }
}
#endif


text:
package com.siyeh.ipp.concatenation;

import com.intellij.openapi.ide.CopyPasteManager;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.psi.*;
import com.intellij.psi.tree.IElementType;
import com.intellij.util.IncorrectOperationException;
import com.siyeh.ipp.base.Intention;
import com.siyeh.ipp.base.PsiElementPredicate;
import com.siyeh.ipp.psiutils.ExpressionUtils;
import org.jetbrains.annotations.NotNull;

import java.awt.datatransfer.StringSelection;
import java.awt.datatransfer.Transferable;

public class CopyConcatenatedStringToClipboardIntention extends Intention {

    @Override @NotNull
    protected PsiElementPredicate getElementPredicate() {
        return new SimpleStringConcatenationPredicate();
    }

    @Override
    protected void processIntention(@NotNull PsiElement element)
            throws IncorrectOperationException {
        if (!(element instanceof PsiBinaryExpression)) {
            return;
        }
        PsiBinaryExpression concatenationExpression =
                (PsiBinaryExpression) element;
        PsiElement parent = concatenationExpression.getParent();
        while (parent instanceof PsiBinaryExpression) {
            final PsiBinaryExpression binaryExpression =
                    (PsiBinaryExpression) parent;
            final IElementType tokenType =
                    binaryExpression.getOperationTokenType();
            if (tokenType != JavaTokenType.PLUS) {
                break;
            }
            final PsiType type = binaryExpression.getType();
            if (type == null || !type.equalsToText("java.lang.String")) {
                break;
            }
            concatenationExpression = binaryExpression;
            parent = concatenationExpression.getParent();
        }
        final StringBuilder text = new StringBuilder();
        buildContatenationText(concatenationExpression, text);
        final String string = text.toString();
        final String unescapedString =
                StringUtil.unescapeStringCharacters(string);
        final Transferable contents = new StringSelection(unescapedString);
        CopyPasteManager.getInstance().setContents(contents);
    }

    private static void buildContatenationText(PsiExpression expression,
                                               StringBuilder out) {
        if (expression instanceof PsiLiteralExpression) {
            final String text = expression.getText();
            final PsiType type = expression.getType();
            if (type != null && (type.equalsToText("java.lang.String")
                    || type.equalsToText("char"))) {
                final int textLength = text.length();
                if (textLength > 2) {
                    out.append(text.substring(1, textLength - 1));
                }
            } else {
                out.append(text);
            }
        } else if (expression instanceof PsiBinaryExpression) {
            final PsiBinaryExpression binaryExpression =
                    (PsiBinaryExpression) expression;
            final Object result =
                    ExpressionUtils.computeConstantExpression(expression);
            if (result != null) {
                out.append(result.toString());
            } else {
                final PsiExpression lhs = binaryExpression.getLOperand();
                buildContatenationText(lhs, out);
                final PsiExpression rhs = binaryExpression.getROperand();
                if (rhs != null) {
                    buildContatenationText(rhs, out);
                }
            }
        } else {
            out.append('?');
        }
    }
}


text:
@interface ThirdViewController ()

@end

@implementation ThirdViewController

- (void)loadView {
    [super loadView];

}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"Third View Controller";
    self.view.backgroundColor = [UIColor purpleColor];
    // Do any additional setup after loading the view.

    if (!self.navigationItem.leftBarButtonItem) {
        self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"Menu" style:UIBarButtonItemStylePlain target:self.navigationController action:@selector(menuButtonPressed:)];
    }

    self.navigationController.navigationBarHidden = NO;
}

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

    [self.navigationController setNavigationBarHidden:NO animated:animated];

    NSLog(@"nav controller = %@", self.navigationController.navigationBar);
    NSLog(@"nav bar hidden = %d", self.navigationController.navigationBarHidden);
}

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

    CGRect rect = self.view.frame;
    rect.origin.y += 64.0f;
    self.view.frame = rect;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end


text:
def tally_results(results)
  all_answers = []
  results.each do |result|
    all_answers << result.choice.text
  end
  hashed_answers = {}
  total_responses = all_answers.length
  all_answers.each do |answer|
    if hashed_answers[answer] == nil
      hashed_answers[answer] = 1
    else
      hashed_answers[answer] += 1
    end
  end
  hashed_answers
end

def count_question_responses(choices)
  responses = []
  choices.each do |choice|
    responses << choice.responses.length
  end
  responses.reduce(:+)
end


text:
<?php

use yii\helpers\Html;
use yii\widgets\ActiveForm;

echo ' ';
/* @var $this yii\web\View */
/* @var $model app\modules\admambulancias\models\RevisionestecnicasSearch */
/* @var $form yii\widgets\ActiveForm */
?>

    <?php
    $form = ActiveForm::begin([
                'action' => ['index'],
                'method' => 'get',
    ]);
    ?>

    <?= $form->field($model, 'idRevision') ?>

    <?= $form->field($model, 'Patente') ?>

    <?= $form->field($model, 'Taller') ?>

    <?= $form->field($model, 'FechaCarga') ?>

<?= $form->field($model, 'FechaVigencia') ?>

        <?php // echo $form->field($model, 'Observaciones') ?>

    <?= Html::submitButton('Search', ['class' => 'btn btn-primary']) ?>
    <?= Html::resetButton('Reset', ['class' => 'btn btn-default']) ?>

<?php ActiveForm::end(); ?>