text:
package com.covata.delta.sdk.examples.fileshare;

import com.covata.delta.sdk.DeltaClient;
import com.covata.delta.sdk.DeltaClientConfig;
import com.covata.delta.sdk.exception.DeltaClientException;
import com.covata.delta.sdk.exception.DeltaServiceException;
import com.covata.delta.sdk.model.DeltaIdentity;
import com.covata.delta.sdk.model.DeltaSecret;
import com.google.common.collect.ImmutableMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.crypto.BadPaddingException;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import java.io.File;
import java.io.IOException;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.covata.delta.sdk.examples.fileshare.EncryptionUtil.base64ToBytes;
import static com.covata.delta.sdk.examples.fileshare.EncryptionUtil.bytesToBase64;
import static com.covata.delta.sdk.examples.fileshare.EncryptionUtil.decrypt;
import static com.covata.delta.sdk.examples.fileshare.EncryptionUtil.encrypt;
import static com.covata.delta.sdk.examples.fileshare.EncryptionUtil.generateIV;
import static com.covata.delta.sdk.examples.fileshare.EncryptionUtil.generateSecretKey;
import static com.covata.delta.sdk.examples.fileshare.EncryptionUtil.keyInBase64ToSecretKey;
import static org.apache.commons.codec.digest.DigestUtils.sha256Hex;
import static org.apache.commons.io.FileUtils.readFileToByteArray;
import static org.apache.commons.io.FileUtils.writeByteArrayToFile;

/**
 * FileShare provides a number of abstractions to allow encryption and
 * decryption of arbitrary files, utilising Covata Delta to store and
 * exchange encryption keys with recipients of the file.
 */
public class FileShare {
    private static final Logger LOG = LoggerFactory.getLogger(FileShare.class);

    private static final String CVT = ".cvt";

    private static final int CONNECTION_TIMEOUT_SECONDS = 20;

    private final DeltaClient client;

    private DeltaIdentity identity;

    /**
     * Create a new FileShare instance linked to the given keystore
     * and pass-phrase.
     *
     * @param passPhrase  the pass-phrase for the keystore
     * @param keyStoreLoc the location of the keystore
     * @throws FileShareException on exception instantiating this instance
     */
    public FileShare(String passPhrase, String keyStoreLoc)
            throws FileShareException {
        try {
            DeltaClientConfig config = DeltaClientConfig.builder()
                    .withKeyStorePassword(passPhrase)
                    .withKeyStorePath(keyStoreLoc)
                    .withLogging(false)
                    .withConnectionTimeoutSeconds(CONNECTION_TIMEOUT_SECONDS)
                    .build();

            client = new DeltaClient(config);
            LOG.debug("Successfully created Delta client");
        } catch (DeltaClientException e) {
            throw new FileShareException("Error creating Delta client", e);
        }
    }

    /**
     * Register a new identity with Delta.
     *
     * @return the id of the new identity
     * @throws FileShareException on exception registering new identity
     */
    public String registerIdentity() throws FileShareException {
        checkIdentityNotSet();
        try {
            identity = client.createIdentity();
            LOG.debug("Identity created: {}", identity.getId());
            return identity.getId();
        } catch (DeltaClientException | DeltaServiceException e) {
            throw new FileShareException("Error registering identity", e);
        }
    }

    /**
     * Set the authenticating identity with ths FileShare instance.
     *
     * @param identityId the identity id to associate
     * @throws FileShareException on exception retrieving the given identity
     */
    public void setIdentity(String identityId) throws FileShareException {
        checkIdentityNotSet();
        try {
            identity = client.getIdentity(identityId);
        } catch (DeltaClientException | DeltaServiceException e) {
            throw new FileShareException("Error retrieving identity", e);
        }
    }

    /**
     * Encrypt the given file and create a corresponding secret in Delta.
     * The encrypted file will be created in the same directory as the
     * original file with a <i>.cvt</i> extension. The key used
     * to encrypt the secret is stored in Delta as a Secret.
     *
     * @param filename the file to be encrypted, includng the full path
     * @return the secret id of the created (base) secret
     * @throws FileShareException on exception encrypting the file and creating secret
     */
    public String encryptFile(String filename) throws FileShareException {
        checkIdentitySet();
        try {
            byte[] data = readFileToByteArray(new File(filename));
            byte[] iv = generateIV();
            SecretKey key = generateSecretKey();

            byte[] encryptedData = encrypt(data, key, iv);
            writeByteArrayToFile(new File(filename + CVT), encryptedData);

            DeltaSecret secret = identity.createSecret(bytesToBase64(key.getEncoded()));

            Map<String, String> metadata = new HashMap<>();
            metadata.put("initialisationVector", bytesToBase64(iv));
            metadata.put("sha256Hex", sha256Hex(encryptedData).toLowerCase());
            secret.synchronizeMetadata();
            secret.addMetadata(metadata);
            LOG.debug("Secret created: {}", secret.getId());
            return secret.getId();
        } catch (IOException | NoSuchAlgorithmException |
                NoSuchPaddingException | InvalidAlgorithmParameterException |
                InvalidKeyException | BadPaddingException |
                IllegalBlockSizeException | DeltaClientException |
                DeltaServiceException e) {
            throw new FileShareException("Error encrypting file", e);
        }
    }

    /**
     * Share the given secret with the given identity.
     *
     * @param secretId the secret id of the secret to share
     * @param targetId the identity id of the target identity
     * @return the secret id of the created (derived) secret
     * @throws FileShareException on exception sharing the secret
     */
    public String share(String secretId, String targetId)
            throws FileShareException {
        checkIdentitySet();
        try {
            DeltaSecret sharedSecret = identity.shareSecret(secretId, targetId);
            LOG.debug("Shared secret created: {}", sharedSecret.getId());
            return sharedSecret.getId();
        } catch (DeltaClientException | DeltaServiceException e) {
            throw new FileShareException(e);
        }
    }

    /**
     * Decrypt the given file with the secret that has the given secret id.
     *
     * @param filename the file to be decrypted, including the full path
     * @param secretId the id of the secret containing the encryption key
     * @throws FileShareException on exception decrypting the file
     */
    public void decryptFile(String filename, String secretId)
            throws FileShareException {
        checkIdentitySet();
        try {
            byte[] data = readFileToByteArray(new File(filename));

            DeltaSecret secret = identity.retrieveSecret(secretId);

            checksumMatches(data, secret.getMetadata().get("sha256Hex"));
            SecretKey key = keyInBase64ToSecretKey(secret.getContent());
            byte[] iv = base64ToBytes(secret.getMetadata().get("initialisationVector"));

            byte[] decryptedData = decrypt(data, key, iv);

            String outputName = filename.substring(0, filename.indexOf(CVT));
            writeByteArrayToFile(new File(outputName), decryptedData);

            LOG.debug("File decrypted: {}", outputName);
        } catch (IOException | DeltaClientException | DeltaServiceException |
                NoSuchAlgorithmException | InvalidKeyException |
                NoSuchPaddingException | InvalidAlgorithmParameterException |
                BadPaddingException | IllegalBlockSizeException e) {
            LOG.error("Error decrypting file with name {}", filename);
            throw new FileShareException("Error decrypting file", e);
        }
    }

    /**
     * Decrypt the given file; a secret will be retrieved based on a digest
     * of the file contents.
     *
     * @param filename the file to be decrypted, including the full path
     * @throws FileShareException on exception decrypting the file
     */
    public void decryptFile(String filename)
            throws FileShareException {
        checkIdentitySet();
        try {
            byte[] data = readFileToByteArray(new File(filename));

            List<DeltaSecret> secrets = getBaseSecretBySha256Hex(data);
            secrets = secrets.isEmpty() ? getDerivedSecretBySha256Hex(data) : secrets;

            if (secrets.isEmpty()) {
                throw new FileShareException(
                        "No secrets stored in Delta for this file");
            } else if (secrets.size() != 1) {
                throw new FileShareException(
                        "More than one secret found in Delta for this file");
            } else {
                DeltaSecret secret = secrets.get(0);
                SecretKey key = keyInBase64ToSecretKey(secret.getContent());
                byte[] iv = base64ToBytes(secret.getMetadata().get("initialisationVector"));

                byte[] decryptedData = decrypt(data, key, iv);

                String outputName = filename.substring(0, filename.indexOf(CVT));
                writeByteArrayToFile(new File(outputName), decryptedData);
                LOG.debug("File decrypted: {}", outputName);
            }
        } catch (Exception e) {
            LOG.error("Error decrypting file with name {}", filename);
            throw new FileShareException("Error decrypting file", e);
        }
    }

    private List<DeltaSecret> getBaseSecretBySha256Hex(byte[] data) {
        return client.getBaseSecretsByMetadata(identity.getId(), identity.getId(),
                ImmutableMap.of("sha256Hex", sha256Hex(data.clone()).toLowerCase()), 1, 1);
    }

    private List<DeltaSecret> getDerivedSecretBySha256Hex(byte[] data) {
        return client.getDerivedSecretsByMetadata(identity.getId(), identity.getId(),
                ImmutableMap.of("sha256Hex", sha256Hex(data.clone()).toLowerCase()), 1, 1);
    }

    private void checkIdentitySet() throws FileShareException {
        if (identity == null) {
            throw new FileShareException("An identity has already been set on this instance");
        }
    }

    private void checkIdentityNotSet() throws FileShareException {
        if (identity != null) {
            throw new FileShareException("An identity needs to be set on this instance");
        }
    }

    private void checksumMatches(byte[] data, String expected) throws FileShareException {
        String actual = sha256Hex(data).toLowerCase();
        if (!actual.equals(expected)) {
            throw new FileShareException(
                    String.format("Checksum does not match (got %s, expected %s)", actual, expected));
        }
    }
}


text:
This was generated by using [BuildHX](https://github.com/jgranick/buildhx).

Generating JSCA/JSDuck/JSON output from the titanium-mobile apidoc's is pretty straight forward; Appcelerator has provided [two scripts](https://github.com/appcelerator/titanium_mobile/tree/master/apidoc) that are pretty straight forward to use.

Remember to use JSDuck version `3.10.1` if you plan on building this yourself!

## Supported Titanium Versions
- [3.5.0](https://github.com/momer/haxe_titanium_mobile/releases/tag/3.5.0-rc1)

## Usage
To install into haxelib, run `haxelib git titanium_mobile_externs https://github.com/momer/haxe_titanium_mobile.git <version> haxelib`

As of this update, the latest [version](https://github.com/momer/haxe_titanium_mobile/releases) is 3.5.0-rc1.

Using the externs is straight forward, here's an example from `test/TestFile.hx`:

	package test;

	import titanium.UI;

	class TestFile {
		static public function main():Void {
			var myList = titanium.UI.createLabel({
				color:'#999',
				text:'I am Window 2',
				font:{fontSize:20,fontFamily:'Helvetica Neue'},
				textAlign:'center',
				width:'auto'
			});
			trace('Hello World; test passed.');
		}
	}

which generates

	(function () { "use strict";
	var test = {};
	test.TestFile = function() { };
	test.TestFile.main = function() {
		var myList = Titanium.UI.createLabel({ color : "#999", text : "I am Window 2", font : { fontSize : 20, fontFamily : "Helvetica Neue"}, textAlign : "center", width : "auto"});
		console.log("Hello World; test passed.");
	};
	test.TestFile.main();
	})();

## Building
If you want to build this yourself, you'll have to install my hacked version of BuildHX @ https://github.com/momer/buildhx/tree/bh-jsduck3-updates

Once installed, just run, `haxelib run buildhx build.xml`.

Note: The changes to that BuildHX fork repo were quick and ugly; at the time of this writing, I was in the midst of implementing a dependency graph which I discovered wouldn't be needed if I fixed a weird bug.

tl;dr: Don't hate me for the ugly commits to that buildhx fork.

## Important Note:
The only test available at this time is basically importing all of the classes, and running them (as seen in [test/TestFile.hx](https://github.com/momer/haxe_titanium_mobile/blob/master/test/test/TestFile.hx)). It passes, and creates the JS output without screaming at us for type issues, etc. There may be hidden bugs or parameter issues that may crop up as usage grows. Report these if you run into them!

## Less Important Note:
Yes, it would have been nice to just use the [apidoc yaml files](https://github.com/appcelerator/titanium_mobile/tree/master/apidoc/Titanium), but that would have been more work.

redpajama_set_name: RedPajamaGithub


text: Virtual Hosts Demo


text:
/*ÒýÈëÕ¾µãͨÓÃÑùʽ*/
@import url("../img/main.css");

/*Í·²¿*/
.top{background:url(b_topbg.gif) repeat-x;border-top:1px solid #546388;height:64px;}
.top_logo{background:url(logo.png) 0 0 no-repeat;width:220px;height:31px;}

.top_center{float:left;padding-top:8px;}
.top_center li{float:left;padding:0 2px;}
.top_center li a:link,.top_center li a:visited{display:inline-block;*display:inline; *zoom:1;text-decoration:none;font-family:"ËÎÌå";font-size:14px;color:#acc3e0;text-align:center;height:50px;line-height:20px;cursor:hand;}
.top_center li a:hover{background:url(top_cz_b_iconbg.png) 50% 50% no-repeat;_background:none;_color:#fff;}
.top_center li a.top_cz_text:link,.top_center li a.top_cz_text:visited{display:inline-block;*display:inline; *zoom:1;text-decoration:none;font-family:"ËÎÌå";font-size:14px;color:#acc3e0;text-align:center;height:50px;line-height:20px;cursor:hand;}
.top_center li a.top_cz_text:hover{background:url(top_cz_b_iconbg1.png) 50% 50% no-repeat;_background:none;_color:#fff;}

/*Í·²¿²Ù×÷¼üͼƬ*/
.top_cz_img1{display:block;background:url(top_cz_b_icon1.png) 50% 50% no-repeat;width:46px;height:30px;}
.top_cz_img2{display:block;background:url(top_cz_b_icon2.png) 50% 50% no-repeat;width:46px;height:30px;}
.top_cz_img3{display:block;background:url(top_cz_b_icon3.png) 50% 50% no-repeat;width:46px;height:30px;}
.top_cz_img3a{display:block;background:url(top_cz_b_icon3a.png) 50% 50% no-repeat;width:46px;height:30px;}
.top_cz_img4{display:block;background:url(top_cz_b_icon4.png) 50% 50% no-repeat;width:46px;height:30px;}
.top_cz_img5{display:block;background:url(top_cz_b_icon5.png) 50% 50% no-repeat;width:46px;height:30px;}
.top_cz_img6{display:block;background:url(top_cz_b_icon6.png) 50% 50% no-repeat;width:70px;height:30px;}
.top_cz_img7{display:block;background:url(top_cz_b_icon7.png) 50% 50% no-repeat;width:46px;height:30px;}
.top_cz_img7a{display:block;background:url(top_cz_b_icon7a.png) 50% 50% no-repeat;width:46px;height:30px;}
.top_cz_img8{display:block;background:url(top_cz_b_icon9.png) 50% 50% no-repeat;width:46px;height:30px;}
.top_cz_img8a{display:block;background:url(top_cz_b_icon9a.png) 50% 50% no-repeat;width:46px;height:30px;}

/*²Ëµ¥*/
.Nmenu_menu{float:left;}
.Nmenu_menu li{float:left;line-height:45px;border-right:1px solid #d7d7d7;}
.Nmenu_menu li a:link,.Nmenu_menu li a:visited{float:left;background:url(icon1.png) 10px 50% no-repeat;padding-left:18px;height:45px;padding-right:15px;color:#5c8fbe;font-size:14px;text-decoration:none;font-weight:bold;}
.Nmenu_menu li a:hover{background:#f0f0f0 url(icon1.png) 10px 50% no-repeat;}

.Nmenu_hd li{float:left;padding-top:12px;padding-left:10px;}
a.Nmenu_hdleft:link,a.Nmenu_hdleft:visited{display:block;height:22px;width:22px;background:url(menu_hdleft.png) 50% 50% no-repeat;}
a.Nmenu_hdleft:hover{background:#a3bdd7 url(menu_hdleft1.png) 50% 50% no-repeat;}
a.Nmenu_hdright:link,a.Nmenu_hdright:visited{display:block;height:22px;width:22px;background:url(menu_hdright.png) 50% 50% no-repeat;}
a.Nmenu_hdright:hover{background:#a3bdd7 url(menu_hdright1.png) 50% 50% no-repeat;}

/*ÖмäÄÚÈÝ¡ª¡ª×ó±ß*/
.content_l{width:160px;background:#345888;}
.content_l_gnmenu dl{border-bottom:2px solid #d7d7d7;background:#2f4d77;padding-top:7px;height:32px;width:100%}
.content_l_gnmenu dt{float:left;font-size:14px;color:#fff;font-weight:bold;padding-left:20px;width:100px;}
.content_l_gnmenu dd a:link,.content_l_gnmenu dd a:visited,.content_l_gnmenu dd a:hover{float:left;height:32px;text-decoration:none;width:40px;}
.gnmenu_open{background:url(open_icon1.png) 50% 7px no-repeat;}
.gnmenu_close{background:url(close_icon1.png) 50% 7px no-repeat;}

.content_l_leftmenu dt{height:33px;border-bottom:2px solid #d7d7d7;background:#345888;font-family:"ËÎÌå";}
.content_l_leftmenu dt a:link,.content_l_leftmenu dt a:visited{ font-size:14px;font-weight:bold;color:#fff;text-decoration:none;line-height:33px;height:33px;cursor:hand;text-overflow:ellipsis; white-space:nowrap; overflow:hidden;width:160px;display:block;}
.content_l_leftmenu dt a:hover{background:#2f4d77;color:#acc3e0;}
.content_l_close{background:#2f4d77 url(close_icon2.png) 50% 50% no-repeat;width:33px;height:33px;_height:32px;text-align:center;line-height:33px;margin-right:4px;display:inline-block; *display:inline; *zoom:1; vertical-align:middle;}
.content_l_open{background:#2f4d77 url(open_icon2.png) 50% 50% no-repeat;width:33px;height:33px;text-align:center;_height:32px;line-height:33px;margin-right:4px;display:inline-block; *display:inline; *zoom:1; vertical-align:middle;}

.content_l_2jmenu{background:#e1e1e1;border-right:2px solid #d7d7d7;padding:10px 5px 10px 10px;}
.content_l_2jmenu li{display:block;height:30px;}
.content_l_2jmenu li a:link,.content_l_2jmenu li a:visited{font-family:"ËÎÌå";text-decoration:none;height:30px;background:url(icon2.png) 10px 50% no-repeat;line-height:30px;padding-left:25px;font-size:14px;color:#345888;text-overflow:ellipsis; white-space:nowrap; overflow:hidden;width:115px;display:block;}
.content_l_2jmenu li a:hover{color:#c20808}

/*ÖмäÄÚÈÝ¡ª¡ªÓÒ±ßÄÚÈÝ*/
.button{background:#304e78 url(buttonbg.jpg) 0 100% repeat-x;border:1px solid #1b3457;color:#ffffff;font-family:'microsoft yahei',"ºÚÌå"; font-size:12px;padding:0 14px;*padding:0 7px;height:22px;margin-right:5px;}

/*°æȨ*/
.foot{background:#fff;border-top:1px solid #d7d7d7;height:29px;text-align:center;color:#345888;line-height:29px;}

a.zPushBtnDisabled,a.zPushBtnDisabled:link,a.zPushBtnDisabled:visited,
a.zPushBtnDisabled:hover{ cursor: not-allowed;  }

a.zPushBtnDisabled img,
a.zPushBtnDisabled:hover img{ opacity: 0.5;  filter: gray Alpha(Opacity = 50);  }

a.zPushBtnDisabled b,
a.zPushBtnDisabled:hover b { cursor: not-allowed; color: #999; }


text:
require "pludoni-capistrano/version"

module Pludoni
  module Capistrano
    # Your code goes here...
  end
end


text:
{-# LANGUAGE TemplateHaskell #-}

module Lopc.Enums where

import Database.Persist.TH

data LopcClassification = MajorLopc
                        | MinorLopc
                        | OtherLopc deriving (Show, Read, Eq, Ord)
derivePersistField "LopcClassification"


text:
from __future__ import absolute_import

from pants.dummies.example_transitive_source import add_four

def test_external_method():
  assert add_four(2) == 6


text:
@interface ViewController ()

@end

@implementation ViewController

- (IBAction)queueMoreButtonTapped:(id)sender {
	LNNotification* notification = [LNNotification notificationWithMessage:@"Looks just like the native iOS 7 and iOS 8 banner notifications!"];
	notification.title = @"First Notification";
	notification.date = [[NSDate date] dateByAddingTimeInterval:-60 * 60 * 24];
	notification.soundName = @"demo.aiff";
	notification.defaultAction = [LNNotificationAction actionWithTitle:@"View" handler:^(LNNotificationAction *action) {
		UIAlertView* alert = [[UIAlertView alloc] initWithTitle:notification.title message:@"Notification was tapped!" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
		[alert show];
	}];

	[[LNNotificationCenter defaultCenter] presentNotification:notification forApplicationIdentifier:@"123"];

	notification = [LNNotification notificationWithMessage:@"You can customize most parts of the notification messages."];
	notification.title = @"Another Notification";
	notification.date = [[NSDate date] dateByAddingTimeInterval:-60 * 60 * 24 * 30];
	notification.soundName = @"demo.aiff";
	notification.defaultAction = nil;

	[[LNNotificationCenter defaultCenter] presentNotification:notification forApplicationIdentifier:@"456"];

	notification = [LNNotification notificationWithMessage:@"You can swipe notifications up to dismiss them."];
	notification.title = @"And Another";
	notification.date = [[NSDate date] dateByAddingTimeInterval:-60 * 60 * 24 * 30];
	notification.soundName = @"demo.aiff";
	notification.defaultAction = [LNNotificationAction actionWithTitle:@"View" handler:^(LNNotificationAction *action) {
		UIAlertView* alert = [[UIAlertView alloc] initWithTitle:notification.title message:@"Notification was tapped!" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
		[alert show];
	}];

	[[LNNotificationCenter defaultCenter] presentNotification:notification forApplicationIdentifier:@"789"];

	notification = [LNNotification notificationWithMessage:@"Pretty cool, isn't it?"];
	notification.title = @"Last One";
	notification.soundName = @"demo.aiff";
	notification.defaultAction = nil;

	[[LNNotificationCenter defaultCenter] presentNotification:notification forApplicationIdentifier:@"123"];
}

- (IBAction)changeStyleButtonTapped:(id)sender {
	[LNNotificationCenter defaultCenter].notificationsBannerStyle = ![LNNotificationCenter defaultCenter].notificationsBannerStyle;
}

- (void)viewDidLoad {
	[super viewDidLoad];

	[[LNNotificationCenter defaultCenter] registerApplicationWithIdentifier:@"123" name:@"Notifications Demp App 1" icon:[UIImage imageNamed:@"DemoApp1Icon"] defaultSettings:LNNotificationDefaultAppSettings];
	[[LNNotificationCenter defaultCenter] registerApplicationWithIdentifier:@"456" name:@"Notifications Demp App 2" icon:[UIImage imageNamed:@"DemoApp2Icon"] defaultSettings:LNNotificationDefaultAppSettings];
	[[LNNotificationCenter defaultCenter] registerApplicationWithIdentifier:@"789" name:@"Notifications Demp App 3" icon:[UIImage imageNamed:@"DemoApp3Icon"] defaultSettings:LNNotificationDefaultAppSettings];

	LNNotification* notification = [LNNotification notificationWithMessage:@"Welcome to LNNotificationsUI!"];
	notification.title = @"Hello World!";
	notification.soundName = @"demo.aiff";
	notification.defaultAction = [LNNotificationAction actionWithTitle:@"View" handler:^(LNNotificationAction *action) {
		UIAlertView* alert = [[UIAlertView alloc] initWithTitle:notification.title message:@"Notification was tapped!" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
		[alert show];
	}];

	[[LNNotificationCenter defaultCenter] presentNotification:notification forApplicationIdentifier:@"123"];
}

- (UIStatusBarStyle)preferredStatusBarStyle
{
	return UIStatusBarStyleLightContent;
}

- (IBAction)unwindToThisViewController:(UIStoryboardSegue *)unwindSegue
{
}

@end


text:
from django.contrib import admin

from city.models import *

admin.site.register(City)


text:
@interface NMSSHChannelTests () {
    NSDictionary *settings;
    NSString *localFilePath;

    NMSSHChannel *channel;
    NMSSHSession *session;
}
@end

@implementation NMSSHChannelTests

// -----------------------------------------------------------------------------
// TEST SETUP
// -----------------------------------------------------------------------------

- (void)setUp {
    settings = [ConfigHelper valueForKey:@"valid_password_protected_server"];

    session = [NMSSHSession connectToHost:[settings objectForKey:@"host"]
                             withUsername:[settings objectForKey:@"user"]];
    [session authenticateByPassword:[settings objectForKey:@"password"]];
    assert([session isAuthorized]);

    // Setup test file for SCP
    localFilePath = [@"~/nmssh-test.txt" stringByExpandingTildeInPath];
    NSData *contents = [@"hello" dataUsingEncoding:NSUTF8StringEncoding];
    [[NSFileManager defaultManager] createFileAtPath:localFilePath
                                            contents:contents
                                          attributes:nil];
}

- (void)tearDown {
    if (channel) {
        channel = nil;
    }

    if (session) {
        [session disconnect];
        session = nil;
    }

    // Cleanup SCP test files
    if ([[NSFileManager defaultManager] fileExistsAtPath:localFilePath]) {
        [[NSFileManager defaultManager] removeItemAtPath:localFilePath
                                                   error:nil];
    }
}

// -----------------------------------------------------------------------------
// SHELL EXECUTION TESTS
// -----------------------------------------------------------------------------

- (void)testCreatingChannelWorks {
    XCTAssertNoThrow(channel = [[NMSSHChannel alloc] initWithSession:session],
                    @"Setting up channel does not throw exception");
}

- (void)testExecutingShellCommand {
    channel = [[NMSSHChannel alloc] initWithSession:session];

    NSError *error = nil;
    XCTAssertNoThrow([channel execute:[settings objectForKey:@"execute_command"]
                               error:&error],
                    @"Execution should not throw an exception");

    XCTAssertEqualObjects([channel lastResponse],
                         [settings objectForKey:@"execute_expected_response"],
                         @"Execution returns the expected response");
}

// -----------------------------------------------------------------------------
// SCP FILE TRANSFER TESTS
// -----------------------------------------------------------------------------

- (void)testUploadingFileToWritableDirWorks {
    channel = [[NMSSHChannel alloc] initWithSession:session];
    NSString *dir = [settings objectForKey:@"writable_dir"];
    XCTAssertTrue([dir hasSuffix:@"/"], @"Directory must end with a slash");

    BOOL result;
    XCTAssertNoThrow(result = [channel uploadFile:localFilePath to:dir],
                    @"Uploading file to writable dir doesn't throw exception");

    XCTAssertTrue(result, @"Uploading to writable dir should work.");
}

- (void)testUploadingFileToNonWritableDirFails {
    channel = [[NMSSHChannel alloc] initWithSession:session];
    NSString *dir = [settings objectForKey:@"non_writable_dir"];

    BOOL result;
    XCTAssertNoThrow(result = [channel uploadFile:localFilePath to:dir],
                    @"Uploading file to non-writable dir doesn't throw"
                    @"exception");

    XCTAssertFalse(result, @"Uploading to non-writable dir should not work.");
}

- (void)testDownloadingExistingFileWorks {
    channel = [[NMSSHChannel alloc] initWithSession:session];

    [[NSFileManager defaultManager] removeItemAtPath:localFilePath error:nil];
    NSString *remoteFile = [[settings objectForKey:@"writable_dir"] stringByAppendingPathComponent:@"nmssh-test.txt"];

    BOOL result;
    XCTAssertNoThrow(result = [channel downloadFile:remoteFile to:localFilePath],
                    @"Downloading existing file doesn't throw exception");

    XCTAssertTrue(result, @"Downloading existing file should work.");
    XCTAssertTrue([[NSFileManager defaultManager] fileExistsAtPath:localFilePath],
                 @"A file has been created");
}

- (void)testDownloadingNonExistingFileFails {
    channel = [[NMSSHChannel alloc] initWithSession:session];

    [[NSFileManager defaultManager] removeItemAtPath:localFilePath error:nil];
    NSString *remoteFile = [NSString stringWithFormat:@"%@nmssh-test.txt",
                            [settings objectForKey:@"non_writable_dir"]];

    BOOL result;
    XCTAssertNoThrow(result = [channel downloadFile:remoteFile to:localFilePath],
                    @"Downloading non-existing file doesn't throw exception");

    XCTAssertFalse(result, @"Downloading non-existing file should not work.");
    XCTAssertFalse([[NSFileManager defaultManager] fileExistsAtPath:localFilePath],
                 @"A file has not been created");
}

@end


text:
Derpibooru-Scraper
==================

Ever wanted to automatically download every image from your Derpibooru feed? Or perhaps the front page?

Well now you can!

Installation
============

You'll need to download and install [mechanize](http://wwwsearch.sourceforge.net/mechanize/) for this program to work.

You'll also need [Python](http://python.org/downloads/) installed to run this script.

Once installed, simply run `python Derpibooru Parsing Bot.py`.

### Supports:

- Logging in to Derpiboo.ru
- Downloading images from front page to folder
- Downloading images from Derpibooru feed to folder
- Naming images sequentially and numerically

### To do:

- Specify image download folder
- Specify how many pages to download
- Continue naming of images count from last run
- Add prefixes and suffixes to downloaded image names


text:
module phosphor.virtualdom {

import emptyArray = utility.emptyArray;
import emptyObject = utility.emptyObject;

/**
 * A typedef for a factory child argument.
 */
export
type FactoryChild = (string | Elem) | (string | Elem)[];

/**
 * A factory function which creates an elem instance.
 */
export
interface IFactory<T extends IData> {
  /**
   * Create an elem instance with the given children.
   */
  (...children: FactoryChild[]): Elem;

  /**
   * Create an elem instance with the given data and children.
   */
  (data: T, ...children: FactoryChild[]): Elem;
}

/**
 * Create an elem factory function for the given tag.
 *
 * This will typically be used to create an elem factory function for
 * a user defined component. The `virtualdom` module exports a `dom`
 * object which contains factories for the standard DOM elements.
 */
export
function createFactory<T extends IData>(tag: string | IComponentClass<T>): IFactory<T> {
  return factory.bind(void 0, tag);
}

/**
 * Extend the first array with elements of the second.
 *
 * Falsey values in the second array are ignored.
 */
function extend(first: any[], second: any[]): void {
  for (var i = 0, n = second.length; i < n; ++i) {
    var item = second[i];
    if (item) first.push(item);
  }
}

/**
 * The elem factory function implementation.
 *
 * When bound to a tag, this function implements `IFactory`.
 */
function factory(tag: ElemTag, first?: any): Elem {
  var data: any = null;
  var children: any[] = null;

  if (first) {
    if (typeof first === 'string') {
      children = [first];
    } else if (first instanceof Elem) {
      children = [first];
    } else if (first instanceof Array) {
      children = first.slice();
    } else {
      data = first;
    }
  }

  var count = arguments.length;
  if (count > 2) {
    children = children || [];
    for (var i = 2; i < count; ++i) {
      var child = arguments[i];
      if (child instanceof Array) {
        extend(children, child);
      } else if (child) {
        children.push(child);
      }
    }
  }

  if (children) {
    for (var i = 0, n = children.length; i < n; ++i) {
      var child = children[i];
      if (typeof child === 'string') {
        children[i] = new Elem(ElemType.Text, child, emptyObject, emptyArray);
      }
    }
  }

  data = data || emptyObject;
  children = children || emptyArray;

  var elem: Elem;
  if (typeof tag === 'string') {
    elem = new Elem(ElemType.Node, tag, data, children);
  } else {
    elem = new Elem(ElemType.Component, tag, data, children);
  }

  return elem;
}

} // module phosphor.virtualdom


text:
"""Initial schema

Revision ID: 1bf4e4e7b24f
Revises:
Create Date: 2020-07-26 08:46:28.752972

"""

from alembic import op
import sqlalchemy as sa

revision = '1bf4e4e7b24f'
down_revision = None
branch_labels = None
depends_on = None

def upgrade():
    metadata = sa.MetaData()

    sa.Table(
        'snippets', metadata,

        # an internal autoincrementing identifier; only used in foreign keys
        sa.Column('id', sa.Integer, primary_key=True),
        # a short unique snippet identifier visible to users
        sa.Column('slug', sa.String(32), nullable=False),

        sa.Column('title', sa.Text),
        sa.Column('syntax', sa.Text),
        sa.Column('created_at', sa.DateTime(timezone=True),
                  server_default=sa.func.now(), nullable=False),
        sa.Column('updated_at', sa.DateTime(timezone=True),
                  server_default=sa.func.now(), nullable=False),

        # slugs must be unique (this will also automatically create a unique index)
        sa.UniqueConstraint('slug', name='uq_slug'),

        # will be used for pagination; slug guarantees uniqueness of the sorting key
        sa.Index('snippets_created_at_slug', 'created_at', 'slug'),
        sa.Index('snippets_updated_at_slug', 'updated_at', 'slug'),
    )

    sa.Table(
        'changesets', metadata,

        # an internal autoincrementing identifier; only used in foreign keys
        sa.Column('id', sa.Integer, primary_key=True),
        sa.Column('snippet_id', sa.Integer, nullable=False),

        # numeric index used to determine the ordering of changesets for a given snippet
        sa.Column('version', sa.Integer,
                  server_default=sa.text('0'), nullable=False),
        sa.Column('content', sa.Text, nullable=False),
        sa.Column('created_at', sa.DateTime(timezone=True),
                  server_default=sa.func.now(), nullable=False),
        sa.Column('updated_at', sa.DateTime(timezone=True),
                  server_default=sa.func.now(), nullable=False),

        # there can be multiple changesets per snippet; changesets should be
        # deleted when the parent snippet is deleted
        sa.ForeignKeyConstraint(['snippet_id'], ['snippets.id'],
                                ondelete='CASCADE', name='fk_snippet',
                                use_alter=False),
        # each changeset is supposed to have a unique version number
        sa.UniqueConstraint('snippet_id', 'version',
                            name='uq_version'),
        # sanity check: do not allow empty changesets
        sa.CheckConstraint('LENGTH(content) > 0',
                           name='check_not_empty'),
        # sanity check: version numbers are non-negative integers
        sa.CheckConstraint('version >= 0',
                           name='check_non_negative_version')

    )

    # tags could have been associated with snippets as M:M via an auxiliary table,
    # but Diesel only supports child-parent associations, so let's do that instead
    sa.Table(
        'tags', metadata,

        # an internal autoincrementing identifier; only used in foreign keys
        sa.Column('id', sa.Integer, primary_key=True),
        sa.Column('snippet_id', sa.Integer, nullable=False),

        sa.Column('value', sa.Text, nullable=False),

        # there can be multiple tags per snippet; tags should be deleted when
        # the parent snippet is deleted
        sa.ForeignKeyConstraint(['snippet_id'], ['snippets.id'],
                                ondelete='CASCADE',
                                name='fk_snippet'),

        # do not allow to abuse the tags for storing too much data
        sa.CheckConstraint('LENGTH(value) < 128', name='check_length'),
        # do not allow repeated tags per snippet
        sa.UniqueConstraint('snippet_id', 'value', name='uq_snippet_tag'),
    )

    metadata.create_all(op.get_bind())

def downgrade():
    op.drop_table('tags')
    op.drop_table('changesets')
    op.drop_table('snippets')


text:
<?php

/* @var $installer Mage_Core_Model_Resource_Setup */
$installer = $this;
$installer->startSetup();
$installer->getConnection()->changeColumn(
    $installer->getTable('tax/tax_calculation_rate'),
    'tax_postcode',
    'tax_postcode',
    'VARCHAR(21) NULL DEFAULT NULL'
);
$installer->endSetup();