text:
"""Downloads WebRTC resources files from a remote host."""

from optparse import OptionParser
from urlparse import urljoin
import os
import shutil
import sys
import tarfile
import tempfile
import urllib2

DESIRED_VERSION = 16
REMOTE_URL_BASE = 'http://commondatastorage.googleapis.com/webrtc-resources'
VERSION_FILENAME = 'webrtc-resources-version'
FILENAME_PREFIX = 'webrtc-resources-'
EXTENSION = '.tgz'
RELATIVE_OUTPUT_PATH = '../../'

def main():
  """
  Downloads WebRTC resources files from a remote host.

  This script will download WebRTC resource files used for testing, like audio
  and video files. It will check the current version in the DEPS file and
  compare it with the one downloaded (kept in a text file in the download dir).
  If the DEPS version is different than the one downloaded, the correct version
  will be downloaded.
  """

  # Make it possible to skip download using an environment variable:
  if os.getenv('WEBRTC_SKIP_RESOURCES_DOWNLOAD'):
    print 'Skipping resources download since WEBRTC_SKIP_RESOURCES_DOWNLOAD set'
    return

  # Define and parse arguments.
  parser = OptionParser()
  parser.add_option('-f', '--force', action='store_true', dest='force',
                    help='forces download and removal of existing resources.')
  parser.add_option('-b', '--base_url', dest='base_url',
                    help= 'Overrides the default Base URL (%s) and uses the '
                    'supplied URL instead.' % REMOTE_URL_BASE)
  parser.add_option('-p', dest='path', help= 'path of resources directory'
                    'relative to this script', default=RELATIVE_OUTPUT_PATH)
  options = parser.parse_args()[0]

  project_root_dir = os.path.normpath(sys.path[0] + '/' + options.path)
  downloads_dir = os.path.join(project_root_dir, 'resources')
  current_version_file = os.path.join(downloads_dir, VERSION_FILENAME)

  # Ensure the downloads dir is created.
  if not os.path.isdir(downloads_dir):
    os.mkdir(downloads_dir)

  # Download archive if forced or DEPS version is different than our current.
  current_version = _get_current_version(current_version_file)
  if DESIRED_VERSION != current_version or options.force:
    base_url = options.base_url or REMOTE_URL_BASE
    _perform_download(base_url, DESIRED_VERSION, downloads_dir)
  else:
    print 'Already have correct version: %s' % current_version

def _get_current_version(current_version_file):
  """Returns the version already downloaded (if any).

  Args:
      current_version_file: The filename of the text file containing the
          currently downloaded version (if any) on local disk.
  Returns:
      The version number, or 0 if no downloaded version exists.
  """
  current_version = 0
  if os.path.isfile(current_version_file):
    f = open(current_version_file)
    current_version = int(f.read())
    f.close()
    print 'Found downloaded resources: version: %s' % current_version
  return current_version

def _perform_download(base_url, desired_version, downloads_dir):
  """Performs the download and extracts the downloaded resources.

  Args:
      base_url: URL that holds the resource downloads.
      desired_version: Desired version, which decides the filename.
  """
  temp_dir = tempfile.mkdtemp(prefix='webrtc-resources-')
  try:
    archive_name = '%s%s%s' % (FILENAME_PREFIX, desired_version, EXTENSION)
    # urljoin requires base URL to end with slash to construct a proper URL
    # to our file:
    if not base_url[-1:] == '/':
      base_url += '/'
    remote_archive_url = urljoin(base_url, archive_name)
    # Download into the temporary directory with display of progress, inspired
    # by the Stack Overflow post at http://goo.gl/JIrbo
    temp_filename = os.path.join(temp_dir, archive_name)
    print 'Downloading: %s' % remote_archive_url

    response = urllib2.urlopen(remote_archive_url)
    temp_file = open(temp_filename, 'wb')
    meta = response.info()
    file_size_kb = int(meta.getheaders('Content-Length')[0]) / 1024
    print 'Progress: %s : %s kB' % (archive_name, file_size_kb)

    file_size_dl_kb = 0
    block_size = 65536
    while True:
      file_buffer = response.read(block_size)
      if not file_buffer:
        break
      file_size_dl_kb += len(file_buffer) / 1024
      temp_file.write(file_buffer)
      status = r'%10d kB [%3.2f%%]' % (file_size_dl_kb,
                                       file_size_dl_kb * 100. / file_size_kb)
      status += chr(8) * (len(status) + 1)
      print status,
    print
    temp_file.close()

    # Clean up the existing resources dir.
    print 'Removing old resources in %s' % downloads_dir
    shutil.rmtree(downloads_dir)
    os.mkdir(downloads_dir)

    # Extract the archive.
    archive = tarfile.open(temp_filename, 'r:gz')
    archive.extractall(downloads_dir)
    archive.close()
    print 'Extracted resource files into %s' % downloads_dir

    # Write the downloaded version to a text file in the resources dir to avoid
    # re-download of the same version in the future.
    new_version_filename = os.path.join(downloads_dir, VERSION_FILENAME)
    version_file = open(new_version_filename, 'w')
    version_file.write('%d' % desired_version)
    version_file.close()

  finally:
    # Clean up the temp dir.
    shutil.rmtree(temp_dir)

if __name__ == '__main__':
  main()


text:
define([
  "jquery",
  "js/components/Content"
], function ($, Content) {
  "use strict";

  var content = new Content();
});

redpajama_set_name: RedPajamaGithub


text:
#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QFontDatabase>
#include <QDebug>

int main(int argc, char *argv[])
{
    QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
    QGuiApplication app(argc, argv);

    // 添加字体文件
    int fontId = QFontDatabase::addApplicationFont(":/Font/fontawesome-webfont.ttf");
    QStringList fontFamilies = QFontDatabase::applicationFontFamilies(fontId);
    qDebug() << "fontFamilies.size() " << fontFamilies.size();

    QQmlApplicationEngine engine;
    engine.load(QUrl(QLatin1String("qrc:/main.qml")));

    return app.exec();
}


text:
from rgw_admin.schema import Schema
from rgw_admin import fields

class KeyEntry(Schema):
    user = fields.StringField()
    secret_key = fields.StringField()
    access_key = fields.StringField()

class User(Schema):
    display_name = fields.StringField()
    user_id = fields.StringField()
    email = fields.StringField()
    keys = fields.ListField(KeyEntry)
    suspended = fields.IntegerField()
    max_buckets = fields.IntegerField()
    tenant = fields.StringField()
    swift_keys = fields.AnyField()
    caps = fields.AnyField()
    subusers = fields.AnyField()

class Category(Schema):
    name = fields.StringField(attribute='category')
    sent_bytes = fields.IntegerField(attribute='bytes_sent')
    requests = fields.IntegerField(attribute='ops')
    successful_requests = fields.IntegerField(attribute='successful_ops')
    received_bytes = fields.IntegerField(attribute='bytes_received')

class BucketUsage(Schema):
    name = fields.StringField(attribute='bucket')
    datetime = fields.StringField(attribute='time')
    owner_id = fields.StringField(attribute='owner')
    timestamp = fields.IntegerField(attribute="epoch")
    categories = fields.ListField(Category)

    def get_requests(self):
        return sum(category.requests for category in self.categories)

    def get_successful_requests(self):
        return sum(category.successful_requests for category in self.categories)

    def get_sent_bytes(self):
        return sum(category.sent_bytes for category in self.categories)

    def get_received_bytes(self):
        return sum(category.received_bytes for category in self.categories)

class UsageEntry(Schema):
    user_id = fields.StringField(attribute='user')
    buckets = fields.ListField(BucketUsage)

class Usage(Schema):
    entries = fields.ListField(UsageEntry)

class BucketSize(Schema):
    size_kb_actual = fields.IntegerField()
    size_kb = fields.IntegerField()
    num_objects = fields.IntegerField()

class Bucket(Schema):
    name = fields.StringField(attribute='bucket')
    owner = fields.StringField()
    size = fields.DictField(
        key=fields.StringField(),
        value=BucketSize,
        attribute='usage'
    )
    zonegroup_id = fields.StringField(attribute='zonegroup')
    marker = fields.StringField()
    id = fields.StringField()
    master_ver = fields.StringField()
    bucket_quota = fields.AnyField()
    ver = fields.StringField()
    mtime = fields.StringField()
    max_marker = fields.StringField()

    @property
    def size_kb_actual(self):
        return sum(size.size_kb_actual for size in self.size.values())

    @property
    def size_kb(self):
        return sum(size.size_kb for size in self.size.values())

    @property
    def num_objects(self):
        # The rgw.none filter exists because of a bug in ceph, just remove it:
        # http://tracker.ceph.com/issues/37942
        return sum(size.num_objects for key, size in self.size.items()
                   if key != 'rgw.none')

BucketList = fields.ListField(Bucket)
KeyEntryList = fields.ListField(KeyEntry)


text:
package com.tyrfing.games.tyrlib3.pc.view.graphics.renderer;

import javax.media.opengl.GL3;
import javax.media.opengl.GLAutoDrawable;
import javax.media.opengl.GLEventListener;

import com.tyrfing.games.tyrlib3.OpenGLActivity;
import com.tyrfing.games.tyrlib3.view.graphics.TyrGL;
import com.tyrfing.games.tyrlib3.view.graphics.renderer.OpenGLRenderer;

public class PCOpenGLRenderer extends OpenGLRenderer implements GLEventListener {

	//private int[] fbo = new int[1];
	//private int[] rbo = new int[2];

	private OpenGLActivity activity;

	public PCOpenGLRenderer(OpenGLActivity activity) {
		super();
		this.activity = activity;
	}

	@Override
	public void init(GLAutoDrawable drawable) {
		System.out.println("Initialized drawable window for PCOpenGLRenderer");
		try {
			TyrGL.IMPL = new PCGL3(drawable.getGL().getGL3());

			defaultSetup();
			activity.loadShaders();

			drawable.getGL().glEnable(GL3.GL_VERTEX_PROGRAM_POINT_SIZE);

			startRendering();
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException("Fatal error encountered!");
		}
	}

	@Override
	public void dispose(GLAutoDrawable drawable) {
		System.out.println("Disposing of OpenGL Context");
	}

	@Override
	public void display(GLAutoDrawable drawable) {
		render();
	}

	@Override
	public void reshape(GLAutoDrawable drawable, int x, int y, int width, int height) {
		surfaceChanged(width, height);
	}

}


text:
from mongoengine import StringField, ReferenceField, ListField, EmailField, DateTimeField

from .mongo import BaseDocument, EnumField
from .utils import enum

IncidentRoles = enum('IncidentRoles', COMMANDER='commander',
                     COMMUNICATIONS='communications',
                     TEAM_MEMBER='team_member')

class Organization(BaseDocument):

    name = StringField()

class Project(BaseDocument):

    name = StringField()
    organization = ReferenceField('Organization')

class User(BaseDocument):

    name = StringField()
    email = StringField()
    organization = ReferenceField('Organization')

class Incident(BaseDocument):

    name = StringField()
    project = ReferenceField('Project')
    severity = EnumField(('high', 'medium', 'low'))

    # Curious if this is the best way to do this.  Maybe we should
    # have a UserRole object.  So an incident has many UserRoles
    # and a UserRole says what role the user plays in the incident
    incident_commander = ReferenceField('User')
    communications = ReferenceField('User')
    team = ListField(ReferenceField('User'))
    sit_rep = ReferenceField('SituationReport')

    start_time = DateTimeField()
    resolution_time = DateTimeField

class SituationReport(BaseDocument):
    """ A good sitrep provides information to active incident responders, helps new responders get quickly up to date
    about the situation, and gives context to other observers like customer support staff.

    The Content should markdown friendly
    """
    content = StringField()

class Update(BaseDocument):
    """
    An Incident has many updates -- which are communications that go to users that are observing the projects
    """
    message = StringField()
    incident = ReferenceField('Incident')

class Subscriber(BaseDocument):
    """Represents a user who is interested in getting updates about a certain project"""
    meta = {'allow_inheritance': True}
    project = ReferenceField('Project')

class EmailSubscriber(Subscriber):
    email = EmailField()

# class SMSSubscriber(Subscriber):
#     telephone_number = StringField()

# class SlackSubscriber(Subscriber)
#


text:
<!doctype html>

<meta charset="utf-8">
<title>Jours 1, 2 et 3 – Harpe laser DAWIN</title>
<meta name="description" content="Résumé des jours 1, 2 et 3">
<meta name="keywords" content="projetDAWIN, arduino, github">

<meta name="twitter:card" content="summary_large_image">
<meta name="twitter:image" content="http://laserharpdawin.github.io/images/banniere-6.jpg">

<meta name="twitter:title" content="Jours 1, 2 et 3">
<meta name="twitter:description" content="Résumé des jours 1, 2 et 3">
<meta name="twitter:creator" content="@laserharpdawin">

<meta property="og:locale" content="en_US">
<meta property="og:type" content="article">
<meta property="og:title" content="Jours 1, 2 et 3">
<meta property="og:description" content="Résumé des jours 1, 2 et 3">
<meta property="og:url" content="/journal/jour-1-2-et-3/">
<meta property="og:site_name" content="Harpe laser DAWIN">

<meta name="google-site-verification" content="googlee0c52dd76436f8f5">

<link rel="canonical" href="/journal/jour-1-2-et-3/">
<link href="/feed.xml" type="application/atom+xml" rel="alternate" title="Harpe laser DAWIN Feed">
<link rel="author" href="https://google.com/+yourid?rel=author">

<meta name="HandheldFriendly" content="True">
<meta name="MobileOptimized" content="320">
<meta name="viewport" content="width=device-width, initial-scale=1.0">

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

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

<meta http-equiv="cleartype" content="on">

<link rel="shortcut icon" href="/favicon.ico">

<link rel="shortcut icon" href="/favicon.png">

<link rel="apple-touch-icon-precomposed" href="/images/apple-touch-icon-precomposed.png">

<link rel="apple-touch-icon-precomposed" sizes="72x72" href="/images/apple-touch-icon-72x72-precomposed.png">

<link rel="apple-touch-icon-precomposed" sizes="114x114" href="/images/apple-touch-icon-114x114-precomposed.png">

<link rel="apple-touch-icon-precomposed" sizes="144x144" href="/images/apple-touch-icon-144x144-precomposed.png">

	<button class="dl-trigger">Open Menu</button>

Accueil

			A propos
			 -->

			Postes

Tous les postes

Tous les Tags

Twitter

Jours 1, 2 et 3

<time datetime="2015-01-22T08:39:48+01:00">January 22, 2015</time>

          Temps de lecture ~2 minutes

 Début du projet

Jour 1

Premier jour pour toute l'équipe sur la technologie Arduino. En possession du starter kit nous nous sommes lancés dans les premiers tutoriels. Une nette impression se dégage, 90% de notre travail sera basé sur de la construction électronique et non du code.

Mise en place du Twitter (@laserHarpDawin) pour permettre une plus grande visibilité de notre projet. Cela permet aux personnes intéressées de suivre notre avancement au fil du temps.

Nous avons également commencé les tests avec le laser, branchements, soudures, code … Mais rien ne semble le faire fonctionner. Plus nous avançons plus nous nous disons que c'est peut être le composant en lui même qui ne fonctionne pas … Demain nous aurons accès à un voltmètre. Nous pourrons "déboguer" les composants.

Jour 2

Nous avons enfin réussi à faire fonctionner un laser ! En effet, nous avions deux lasers à notre disposition, et tous les tests ont été réalisés jusqu'à aujourd'hui sur un seul. Il ne fonctionnait pas. Nous avons donc aujourd'hui essayé l'autre laser, qui lui a fonctionné du premier coup ou presque. C'était au final un problème lié au matériel, et ce ne sera sans doute pas le dernier …

Nous nous sommes rendus compte, une fois de plus, d'un soucis d'ordre matériel. Il nous manque certains composants permettant de relier d'autres composants essentiels les uns aux autres. Ainsi, même si le laser fonctionne, il nous est impossible pour le moment de tester le moteur ou l'interface midi. Nous avons étudié chaque cas sous tous  les angles, et dès que nous pourrons obtenir le matériel désiré, nous serons aptes à tester immédiatement ces nouveaux composants.

Nous avons aujourd'hui réalisé un logo qui sert à la fois de photo de profil pour notre compte Twitter (@laserHarpDawin) et de logo pour notre site web. Cette harpe a été réalisée par Thomas en s'inspirant de plusieurs logos de harpes similaires (tel celui de Guinness). Cependant, on notera que notre harpe représente une harpe pouvant être posée sur le sol, alors que le logo de Guinness représente une harpe portative.

Jour 3

Par manque de moyens techniques (composants), nous n'avons pas pu avancer concrètement sur la harpe, ou la manipulation de l'Arduino. Nous nous sommes donc concentrés sur la réalisation à la fois du site, et du rapport préliminaire à rendre à Christine UNY. Nous avons également fait l'inventaire de toutes les pièces qu'il nous manquait et les avons commandé. Avec un peu de chance elles arriveront demain.

Les deux précédents jours de tests nous ont permis d'être surs de ce que nous allions réaliser, et de quoi nous allions réellement avoir besoin. Nous sommes prêts à commencer la construction de la harpe finale, dès que les composants seront livrés.

        projetDAWINarduinogithub

 Like

 Tweet

 +1

      Read More

Bilan Semaine 3

Bilan de la troisième semaine de travail Lire la suite

Livret d'utilisation

        Publier le February 06, 2015

Affiche du projet

        Publier le February 06, 2015

    © 2015 laserHarpDAWIN. Powered by Jekyll using the HPSTR Theme.

    Please enable JavaScript to view the comments powered by Disqus.
    comments powered by Disqus


text:
/*
 * File:   Function.h
 * Author: Rick
 *
 * Created on May 12, 2015, 1:00 AM
 */

#ifndef FUNCTIONS_H
#define	FUNCTIONS_H

#ifndef __DELAY_H
#define FOSC  72000000LL  // clock-frequecy in Hz with suffix LL (64-bit-long), eg. 32000000LL for 32MHz
#define FCY       (FOSC/2)  // MCU is running at FCY MIPS
#define delay_us(x) __delay32(((x*FCY)/1000000L)) // delays x us
#define delay_ms(x) __delay32(((x*FCY)/1000L))  // delays x ms
#define __DELAY_H 1
#include <libpic30.h>
#endif

#define PPSin(fn,pin)    iPPSInput(IN_FN_PPS##fn,IN_PIN_PPS##pin)
#define PPSout(fn,pin)    iPPSOutput(OUT_PIN_PPS##pin,OUT_FN_PPS##fn)

#define RX1_Pin_Map RPINR18bits.U1RXR
#define RX2_Pin_Map RPINR19bits.U2RXR
#define RX3_Pin_Map RPINR27bits.U3RXR
#define RX4_Pin_Map RPINR28bits.U4RXR

#define Pin_42_Output RPOR4bits.RP42R
#define Pin_49_Output RPOR5bits.RP49R
#define Pin_55_Output RPOR6bits.RP55R
#define Pin_56_Output RPOR7bits.RP56R
#define Pin_70_Output RPOR8bits.RP70R

#define TX1_Output 1
#define TX2_Output 3
#define TX3_Output 27
#define TX4_Output 29

extern void UART_init(void);
extern unsigned char Receive_peek(void);
extern int Receive_available(void);
extern unsigned char Receive_get(void);
extern void Send_put(unsigned char _data);

extern void UART1_init(void);
extern unsigned char Receive_peek1(void);
extern int Receive_available1(void);
extern unsigned char Receive_get1(void);
extern void Send_put1(unsigned char _data);

extern void UART2_init(void);
extern unsigned char Receive_peek2(void);
extern int Receive_available2(void);
extern unsigned char Receive_get2(void);
extern void Send_put2(unsigned char _data);

extern void UART3_init(void);
extern unsigned char Receive_peek3(void);
extern int Receive_available3(void);
extern unsigned char Receive_get3(void);
extern void Send_put3(unsigned char _data);

extern void begin(volatile int * ptr, unsigned char maxSize, unsigned char givenAddress, bool error, void (*stufftosend)(unsigned char), unsigned char (*stufftoreceive)(void), int (*stuffavailable)(void), unsigned char (*stuffpeek)(void));
extern void begin1(volatile int * ptr, unsigned char maxSize, unsigned char givenAddress, bool error, void (*stufftosend)(unsigned char), unsigned char (*stufftoreceive)(void), int (*stuffavailable)(void), unsigned char (*stuffpeek)(void));
extern void begin2(volatile int * ptr, unsigned char maxSize, unsigned char givenAddress, bool error, void (*stufftosend)(unsigned char), unsigned char (*stufftoreceive)(void), int (*stuffavailable)(void), unsigned char (*stuffpeek)(void));
extern void begin3(volatile int * ptr, unsigned char maxSize, unsigned char givenAddress, bool error, void (*stufftosend)(unsigned char), unsigned char (*stufftoreceive)(void), int (*stuffavailable)(void), unsigned char (*stuffpeek)(void));

extern volatile int receiveArray[100];
extern volatile int receiveArray1[20];
extern volatile int receiveArray2[20];
extern volatile int receiveArray3[20];

extern void Setup(void);
extern void Delay(int wait);
void PinSetMode(void);

extern void initTimerOne();

#endif	/* FUNCTIONS_H */


text:
from __future__ import absolute_import, unicode_literals

from django.conf.urls import include, url
from wagtail.contrib.wagtailapi import urls as wagtailapi_urls
from wagtail.wagtailadmin import urls as wagtailadmin_urls
from wagtail.wagtailcore import urls as wagtail_urls
from wagtail.wagtaildocs import urls as wagtaildocs_urls
from wagtail.wagtailimages import urls as wagtailimages_urls
from wagtail.wagtailimages.tests import urls as wagtailimages_test_urls
from wagtail.wagtailsearch import urls as wagtailsearch_urls

urlpatterns = [
    url(r'^admin/', include(wagtailadmin_urls)),
    url(r'^search/', include(wagtailsearch_urls)),
    url(r'^documents/', include(wagtaildocs_urls)),
    url(r'^testimages/', include(wagtailimages_test_urls)),
    url(r'^images/', include(wagtailimages_urls)),

    url(r'^api/', include(wagtailapi_urls)),

    url(r'', include(wagtail_urls)),
]


text:
"""Waits for Treadmill application completion.
"""

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals

import logging
import sys

import click

from treadmill import cli
from treadmill import context
from treadmill import utils
from treadmill import zknamespace as z
from treadmill import yamlwrapper as yaml

from treadmill.trace.app import (events, zk)

_LOGGER = logging.getLogger(__name__)

def print_yaml(obj):
    """Print yaml wih correct options."""
    cli.out(yaml.dump(obj,
                      default_flow_style=False,
                      explicit_start=True,
                      explicit_end=True))

class _AppTraceEventsOnly(events.AppTraceEventHandler):
    """Handler used to integrate trace events into final state of the container
    """

    def on_scheduled(self, when, instanceid, server, why):
        """Invoked when task is scheduled.
        """

    def on_pending(self, when, instanceid, why):
        """Invoked when task is pending.
        """

    def on_pending_delete(self, when, instanceid, why):
        """Invoked when task is about to be deleted.
        """

    def on_configured(self, when, instanceid, server, uniqueid):
        """Invoked when task is configured.
        """

    def on_deleted(self, when, instanceid):
        """Invoked when task is deleted.
        """

    def on_finished(self, when, instanceid, server, signal, exitcode):
        """Invoked when task is finished."""
        if exitcode > 255:
            cli.out(
                '%s - %s killed, signal: %s',
                utils.strftime_utc(when),
                instanceid,
                utils.signal2name(signal)
            )
            self.ctx.update(
                {
                    'signal': signal,
                    'when': when,
                    'server': server
                }
            )
        else:
            cli.out(
                '%s - %s exited, return code: %s',
                utils.strftime_utc(when),
                instanceid,
                exitcode
            )
            self.ctx.update(
                {
                    'exitcode': exitcode,
                    'when': when,
                    'server': server
                }
            )

    def on_killed(self, when, instanceid, server, is_oom):
        """Default task-finished handler.
        """

    def on_aborted(self, when, instanceid, server, why):
        """Invoked when task is aborted.
        """

    def on_service_running(self, when, instanceid, server, uniqueid, service):
        """Invoked when service is running.
        """

    def on_service_exited(self, when, instanceid, server, uniqueid, service,
                          exitcode, signal):
        """Suppress stdout/err info."""
        if exitcode > 255:
            cli.out(
                '%s - %s/%s/service/%s killed, signal: %s',
                utils.strftime_utc(when),
                instanceid,
                uniqueid,
                service,
                utils.signal2name(signal)
            )
        else:
            cli.out(
                '%s - %s/%s/service/%s exited, return code: %s',
                utils.strftime_utc(when),
                instanceid,
                uniqueid,
                service,
                exitcode
            )

def init():
    """Top level command handler."""
    # too many branches.
    #
    # pylint: disable=R0912

    @click.command()
    @click.option('--cell', required=True,
                  envvar='TREADMILL_CELL',
                  callback=cli.handle_context_opt,
                  expose_value=False)
    @click.argument('instances', nargs=-1)
    def wait(instances):
        """Wait for all instances to exit."""
        expected_nb = len(instances)
        finished = []

        zkclient = context.GLOBAL.zk.conn
        done_event = zkclient.handler.event_object()
        callback = _AppTraceEventsOnly()

        def _make_watch(instance):
            """Make watch function, closure on zkclient, cell and instance."""

            info = dict(instance=instance)

            @utils.exit_on_unhandled
            def _watch_scheduled(data, _stat, event):
                """Watch on scheduled node."""

                if data is None and event is None:
                    # ZNode is not there yet
                    _LOGGER.info('Waiting for %r', instance)
                    return True

                elif event is not None and event.type == 'DELETED':

                    trace = zk.AppTrace(zkclient, instance, callback)
                    trace.run(snapshot=True, ctx=info)

                    print_yaml(info)

                    finished.append(info)
                    if len(finished) == expected_nb:
                        done_event.set()
                    return False

                else:
                    # ZNode is here, waiting for instance to terminate.
                    return True

            return _watch_scheduled

        for instance in instances:
            # Setup a datawatch on each of the instance's scheduled path
            path_scheduled = z.path.scheduled(instance)
            zkclient.DataWatch(path_scheduled)(
                _make_watch(instance)
            )

        rc = None
        try:
            while not done_event.wait(timeout=1):
                pass
        except KeyboardInterrupt:
            done_event.set()
            rc = -1

        finally:
            zkclient.stop()

        if rc is None:
            # Check for success
            rc = 0
            for info in finished:
                if 'exitcode' in info and info['exitcode'] == 0:
                    _LOGGER.info('%s: ok', info['instance'])
                else:
                    _LOGGER.info('%s: failure', info['instance'])
                    rc = 1

        sys.exit(rc)

    return wait


text:
package zmaster587.advancedRocketry.tile;

import io.netty.buffer.ByteBuf;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.tileentity.TileEntity;
import net.minecraftforge.fml.relauncher.Side;
import zmaster587.libVulpes.inventory.modules.IModularInventory;
import zmaster587.libVulpes.inventory.modules.IToggleButton;
import zmaster587.libVulpes.inventory.modules.ModuleBase;
import zmaster587.libVulpes.inventory.modules.ModuleToggleSwitch;
import zmaster587.libVulpes.network.PacketHandler;
import zmaster587.libVulpes.network.PacketMachine;
import zmaster587.libVulpes.util.INetworkMachine;

import java.util.LinkedList;
import java.util.List;

public class TileDrill extends TileEntity implements IModularInventory, IToggleButton, INetworkMachine {

	private float distanceExtended;
	private boolean extended;
	private ModuleToggleSwitch toggleSwitch;

	public TileDrill() {
		distanceExtended = 0;
	}

	public float getDistanceExtended() {
		return distanceExtended;
	}

	public void setDistanceExtended(float distance) {
		this.distanceExtended = distance;
	}

	public boolean drillExtended() {
		return extended;
	}

	public void setDrillExtended(boolean value) {
		extended = value;
		distanceExtended = value ? 1f : 0f;
	}

	@Override
	public List<ModuleBase> getModules(int id, EntityPlayer player) {
		List<ModuleBase> modules = new LinkedList<ModuleBase>();

		modules.add(toggleSwitch = new ModuleToggleSwitch(160, 5, 0, "", this,  zmaster587.libVulpes.inventory.TextureResources.buttonToggleImage, 11, 26, drillExtended()));

		return modules;
	}

	@Override
	public String getModularInventoryName() {
		return "tile.drill.name";
	}

	@Override
	public boolean canInteractWithContainer(EntityPlayer entity) {
		return true;
	}

	@Override
	public void onInventoryButtonPressed(int buttonId) {

		if(buttonId == 0) {
			this.setDrillExtended(toggleSwitch.getState());
			PacketHandler.sendToServer(new PacketMachine(this,(byte)0));
		}
	}

	@Override
	public void stateUpdated(ModuleBase module) {
		if(module == toggleSwitch)
			setDrillExtended(toggleSwitch.getState());
	}

	@Override
	public void writeDataToNetwork(ByteBuf out, byte id) {
		out.writeBoolean(extended);

	}

	@Override
	public void readDataFromNetwork(ByteBuf in, byte packetId,
			NBTTagCompound nbt) {
		nbt.setBoolean("enabled", in.readBoolean());
	}

	@Override
	public void useNetworkData(EntityPlayer player, Side side, byte id,
			NBTTagCompound nbt) {
		setDrillExtended(nbt.getBoolean("enabled"));
		toggleSwitch.setToggleState(drillExtended());

		//Last ditch effort to update the toggle switch when it's flipped
		if(!world.isRemote)
			PacketHandler.sendToNearby(new PacketMachine(this, (byte)0), world.provider.getDimension(), pos, 64);

	}

	@Override
	public NBTTagCompound writeToNBT(NBTTagCompound nbt) {
		super.writeToNBT(nbt);

		nbt.setFloat("extendAmt", distanceExtended);
		nbt.setBoolean("extended", extended);
		return nbt;
	}

	@Override
	public void readFromNBT(NBTTagCompound nbt) {
		super.readFromNBT(nbt);

		distanceExtended = nbt.getFloat("extendAmt");
		extended = nbt.getBoolean("extended");

	}

}


text:
namespace Ui {
    class Q3AddItemDirector;
}

class Q3AddItemDirector : public Q3Director
{
    Q_OBJECT

public:
    Q3AddItemDirector(QWidget *parent = NULL);
    virtual ~Q3AddItemDirector();

    virtual void setItemType(Q3SceletonItem::Type type);
    virtual bool processClick(QMouseEvent *event, const QPointF &scenePos);
    virtual bool processDragged(const QPointF &oldScenePos,
                                const QPointF &newScenePos);
    virtual bool processMoved(const QPointF &oldScenePos,
                              const QPointF &newScenePos);
    virtual bool processKeyRelease(int key);
    virtual void stop();
    virtual void draw(Q3Painter &painter) const;

protected:
    virtual bool isActive();

public slots:
    void setupAddForm();

private slots:
    void on_createElementButton_clicked();

private:
    Q3SceletonItem *item_;
    Ui::Q3AddItemDirector *ui;
    Q3SceletonItemForm *addForm_;
};

#endif // Q3ADDITEMDIRECTOR_H


text:
describe("Ghost Mode: Utils", function () {

    var ghost;
    var locationStub;

    beforeEach(function () {
        ghost = window.ghost;
        locationStub = sinon.stub(ghost, "getCurrentPath").returns("/path");
    });
    afterEach(function () {
        locationStub.restore();
    });

    it("should allow syncing if Paths match", function () {
        var actual = ghost.canSync("/path");
        assert.equal(actual, true);
    });
    it("should not allow syncing if Paths do not match", function () {
        var actual = ghost.canSync("/path2");
        assert.equal(actual, false);
    });
});


text:
FROM openzipkin/zipkin-base:1.2.2
MAINTAINER OpenZipkin "http://zipkin.io/"

RUN curl -SL $ZIPKIN_REPO/io/zipkin/zipkin-web/$ZIPKIN_VERSION/zipkin-web-$ZIPKIN_VERSION-all.jar > zipkin-web.jar

ADD run.sh /usr/local/bin/run
ENTRYPOINT ["/usr/local/bin/run"]

EXPOSE 8080


text:
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE620_Unverified_Password_Change__w32_12.c
Label Definition File: CWE620_Unverified_Password_Change__w32.label.xml
Template File: point-flaw-12.tmpl.c
*/
/*
 * @description
 * CWE: 620 Unverified Password Change
 * Sinks: w32NetUserSetInfo
 *    GoodSink: Require old password to set new password using NetUserChangePassword()
 *    BadSink : Set new password without verifying the old one using NetUserSetInfo()
 * Flow Variant: 12 Control flow: if(globalReturnsTrueOrFalse())
 *
 * */

#include "std_testcase.h"

#include <windows.h>
#include <lm.h>
#pragma comment(lib, "netapi32.lib")
#define USERNAME L"cwe620testuser"

#ifndef OMITBAD

void CWE620_Unverified_Password_Change__w32_12_bad()
{
    if(globalReturnsTrueOrFalse())
    {
        {
            wchar_t newPassword[256];
            USER_INFO_1003 myUserInfo;
            NET_API_STATUS status;
            myUserInfo.usri1003_password = newPassword;
            printWLine(L"Enter new password: ");
            if (fwscanf(stdin, L"%255s", myUserInfo.usri1003_password) != 1)
            {
                myUserInfo.usri1003_password[0] = L'\0';
            }
            /* FLAW: Set password without verifying the old one */
            status = NetUserSetInfo(NULL, USERNAME, 1003, (LPBYTE)&myUserInfo, NULL);
            if(status == NERR_Success)
            {
                printWLine(L"Success!");
            }
            else
            {
                wprintf(L"NetUserSetInfo failed.  Status = %u = 0x%x\n", status, status);
            }
        }
    }
    else
    {
        {
            wchar_t oldPassword[256];
            wchar_t newPassword[256];
            NET_API_STATUS status;
            printWLine(L"Enter old password: ");
            if (fwscanf(stdin, L"%255s", oldPassword) != 1)
            {
                oldPassword[0] = L'\0';
            }
            printWLine(L"Enter new password: ");
            if (fwscanf(stdin, L"%255s", newPassword) != 1)
            {
                newPassword[0] = L'\0';
            }
            /* FIX: Verify the old password when setting the new password */
            status = NetUserChangePassword(NULL, USERNAME, oldPassword, newPassword);
            if(status == NERR_Success)
            {
                printWLine(L"Success!");
            }
            else
            {
                wprintf(L"NetUserChangePassword failed.  Status = %u = 0x%x\n", status, status);
            }
        }
    }
}

#endif /* OMITBAD */

#ifndef OMITGOOD

/* good1() uses the GoodSink on both sides of the "if" statement */
static void good1()
{
    if(globalReturnsTrueOrFalse())
    {
        {
            wchar_t oldPassword[256];
            wchar_t newPassword[256];
            NET_API_STATUS status;
            printWLine(L"Enter old password: ");
            if (fwscanf(stdin, L"%255s", oldPassword) != 1)
            {
                oldPassword[0] = L'\0';
            }
            printWLine(L"Enter new password: ");
            if (fwscanf(stdin, L"%255s", newPassword) != 1)
            {
                newPassword[0] = L'\0';
            }
            /* FIX: Verify the old password when setting the new password */
            status = NetUserChangePassword(NULL, USERNAME, oldPassword, newPassword);
            if(status == NERR_Success)
            {
                printWLine(L"Success!");
            }
            else
            {
                wprintf(L"NetUserChangePassword failed.  Status = %u = 0x%x\n", status, status);
            }
        }
    }
    else
    {
        {
            wchar_t oldPassword[256];
            wchar_t newPassword[256];
            NET_API_STATUS status;
            printWLine(L"Enter old password: ");
            if (fwscanf(stdin, L"%255s", oldPassword) != 1)
            {
                oldPassword[0] = L'\0';
            }
            printWLine(L"Enter new password: ");
            if (fwscanf(stdin, L"%255s", newPassword) != 1)
            {
                newPassword[0] = L'\0';
            }
            /* FIX: Verify the old password when setting the new password */
            status = NetUserChangePassword(NULL, USERNAME, oldPassword, newPassword);
            if(status == NERR_Success)
            {
                printWLine(L"Success!");
            }
            else
            {
                wprintf(L"NetUserChangePassword failed.  Status = %u = 0x%x\n", status, status);
            }
        }
    }
}

void CWE620_Unverified_Password_Change__w32_12_good()
{
    good1();
}

#endif /* OMITGOOD */

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

#ifdef INCLUDEMAIN

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

#endif


text:
.. _0-8-1-release-notes:

===========
South 0.8.1
===========

This is the first bugfix release in the 0.8 series, to address a critical
regression on older versions of Django.

Major changes are outlined below. A full list of changes can be found on
`the repository <https://bitbucket.org/andrewgodwin/south/commits/all/>`_.

Backwards incompatible changes
==============================

None

Django 1.4 regression
=====================

There was a critical regression with South 0.8 and any version of
Django below 1.5 due to a misimplementation of the index_together code -
this has now been fixed.

keep_default fully deprecated
=============================

The keep_default argument to add_column has been working differently
in different backends for a while, so it is now ignored everywhere
and defaults are never kept in the database.


text:
<resources>
    <string name="app_name">PermisoWrapper - Demo</string>
</resources>


text:
FactoryGirl.define do
  factory :promo_code do
    token "MyString"
    promo_vendor
  end
end


text:
require 'rails'
require "starapi/version"
require 'logging'

module Starapi
  # Configurable informations
  mattr_accessor :namespace
  @@namespace   = "http://www.example.com/RS/webservices/"
  mattr_accessor :service_url
  @@service_url = 'http://www.example.com/READiDataExchange/WSRSDataExchange.asmx'
  mattr_accessor :user
  @@user        = "user"
  mattr_accessor :password
  @@password    = "password"

  mattr_accessor :assure_context_identifier
  @@assure_context_identifier    = "XXXXXXXXXXXXXXXXXXX"

  mattr_accessor :assure_base_url
  @@assure_base_url = "https://xx.assuresign.net/XXX/XXX/vs/XXX.svc"

  mattr_accessor :assure_host
  @@assure_host     = "xx.assuresign.net"

  mattr_accessor :assure_template_id
  @@assure_template_id = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"

  mattr_accessor :assure_user
  @@assure_user = "xxxxxxxxxxxxxxxxx"

  mattr_accessor :assure_password
  @@assure_password = "xxxxxxxxxxxx"

  # Log system
  Logging.init :debug, :info, :warn, :error, :fatal
  layout = Logging::Layouts::Pattern.new :pattern => "[%d] [%-5l] %m\n"
  default_appender = Logging::Appenders::RollingFile.new 'default',
    :filename => "log/starapi.log", :age => 'daily', :keep => 30, :safe => true, :layout => layout

  mattr_accessor :log
  @@log = Logging::Logger[:root]
  @@log.add_appenders default_appender
  @@log.level = :debug

  # Load the dependencies
  autoload :Opsolve, "starapi/opsolve"
  autoload :Assuresign, "starapi/assuresign"

  # To permit Rails style config initalizer
  class << self
    def setup
      yield self
    end
  end
end


text:
void generateFractal(AppState* const, WorkQueueItem const * const);

#endif // GENERATE_FRACTAL_HPP


text:
<?xml version="1.0" encoding="utf-8"?>
<!--
Copyright (C) 2015 The Android Open Source Project

   Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

         http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.
-->
<set
    xmlns:android="http://schemas.android.com/apk/res/android" >
    <objectAnimator
        android:duration="600"
        android:propertyName="strokeColor"
        android:valueFrom="#FFFFFFFF"
        android:valueTo="#FFF3511E"
        android:interpolator="@android:interpolator/fast_out_slow_in" />
    <objectAnimator
        android:duration="600"
        android:propertyName="strokeAlpha"
        android:valueFrom="0.5"
        android:valueTo="1.0"
        android:valueType="floatType"
        android:interpolator="@android:interpolator/fast_out_slow_in" />
    <set
        android:ordering="sequentially" >
        <objectAnimator
            android:duration="166"
            android:propertyName="trimPathOffset"
            android:valueFrom="1.0"
            android:valueTo="1.0"
            android:valueType="floatType"
            android:interpolator="@android:interpolator/linear" />
        <objectAnimator
            android:duration="433"
            android:propertyName="trimPathOffset"
            android:valueFrom="1.0"
            android:valueTo="0.5"
            android:valueType="floatType"
            android:interpolator="@interpolator/trusted_state_to_error_animation_interpolator_2" />
    </set>
    <set
        android:ordering="sequentially" >
        <objectAnimator
            android:duration="166"
            android:propertyName="trimPathStart"
            android:valueFrom="1.0"
            android:valueTo="1.0"
            android:valueType="floatType"
            android:interpolator="@android:interpolator/linear" />
        <objectAnimator
            android:duration="433"
            android:propertyName="trimPathStart"
            android:valueFrom="1.0"
            android:valueTo="0.0"
            android:valueType="floatType"
            android:interpolator="@interpolator/trusted_state_to_error_animation_interpolator_0" />
    </set>
</set>


text:
#pragma once
#include "util/sexpr/sexpr.h"
#include "util/debug.h"

namespace lean {

template<typename F>
void for_each(sexpr const & l, F f) {
    static_assert(std::is_same<typename std::result_of<F(sexpr const &)>::type, void>::value,
                  "foreach: return type of f is not void");
    lean_assert(is_list(l));
    sexpr const * h = &l;
    while (!is_nil(*h)) {
        lean_assert(is_cons(*h));
        f(head(*h));
        h = &tail(*h);
    }
}

template<typename F>
sexpr map(sexpr const & l, F f) {
    static_assert(std::is_same<typename std::result_of<F(sexpr const &)>::type, sexpr>::value,
                  "map: return type of f is not sxpr");
    lean_assert(is_list(l));
    if (is_nil(l)) {
        return l;
    } else {
        lean_assert(is_cons(l));
        auto x = f(head(l)); // force left-to-right evaluation order
        return sexpr(x, map(tail(l), f));
    }
}

template<typename P>
sexpr filter(sexpr const & l, P p) {
    static_assert(std::is_same<typename std::result_of<P(sexpr const &)>::type, bool>::value,
                  "filter: return type of p is not bool");
    lean_assert(is_list(l));
    if (is_nil(l)) {
        return l;
    } else {
        lean_assert(is_cons(l));
        if (p(head(l)))
            return sexpr(head(l), filter(tail(l), p));
        else
            return filter(tail(l), p);
    }
}

template<class T, class BOP>
T foldl(sexpr const & l, T init, BOP op) {
    static_assert(std::is_same<typename std::result_of<BOP(T, sexpr const &)>::type, T>::value,
                  "foldl: return type of op is not T");
    lean_assert(is_list(l));
    if (is_nil(l)) {
        return init;
    } else {
        lean_assert(is_cons(l));
        return foldl(tail(l), op(init, head(l)), op);
    }
}

template<class T, class BOP>
T foldr(sexpr const & l, T init, BOP op) {
    static_assert(std::is_same<typename std::result_of<BOP(sexpr const &, T)>::type, T>::value,
                  "foldr: return type of op is not T");
    lean_assert(is_list(l));
    if (is_nil(l)) {
        return init;
    } else {
        lean_assert(is_cons(l));
        return op(head(l), foldr(tail(l), init, op));
    }
}

template<typename P>
bool forall(sexpr const & l, P p) {
    static_assert(std::is_same<typename std::result_of<P(sexpr const &)>::type, bool>::value,
                  "forall: return type of p is not bool");
    lean_assert(is_list(l));
    if (is_nil(l)) {
        return true;
    } else {
        lean_assert(is_cons(l));
        return p(head(l)) && forall(tail(l), p);
    }
}

template<typename P>
bool contains(sexpr const & l, P p) {
    static_assert(std::is_same<typename std::result_of<P(sexpr const &)>::type, bool>::value,
                  "contains: return type of p is not bool");
    lean_assert(is_list(l));
    sexpr const * h = &l;
    while (!is_nil(*h)) {
        lean_assert(is_cons(*h));
        if (p(head(*h)))
            return true;
        h = &tail(*h);
    }
    return false;
}

template<typename T>
bool member(T const & e, sexpr const & l) {
    lean_assert(is_list(l));
    sexpr const * curr = &l;
    while (!is_nil(*curr)) {
        if (head(*curr) == e)
            return true;
        curr = &tail(*curr);
    }
    return false;
}

template<typename P>
sexpr const * find(sexpr const & l, P p) {
    static_assert(std::is_same<typename std::result_of<P(sexpr const &)>::type, bool>::value,
                  "find: return type of p is not bool");
    lean_assert(is_list(l));
    sexpr const * h = &l;
    while (!is_nil(*h)) {
        lean_assert(is_cons(*h));
        if (p(head(*h)))
            return &(head(*h));
        h = &tail(*h);
    }
    return nullptr;
}

sexpr append(sexpr const & l1, sexpr const & l2);

sexpr reverse(sexpr const & l);

}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DeadManSwitch.UI
{
    public class UserActionEditAllModel
    {
        public UserActionEditAllModel()
        {
            this.UserActions = new List<UserActionEditModel>();

            this.ActionTypeOptions = new Dictionary<string, string>();
            this.WaitMinuteOptions = new Dictionary<string, string>();
        }

        public List<UserActionEditModel> UserActions { get; set; }

        public Dictionary<string, string> ActionTypeOptions { get; set; }
        public Dictionary<string, string> WaitMinuteOptions { get; set; }
    }
}


text:
package Perl::Critic::Exception;

use 5.006001;
use strict;
use warnings;

our $VERSION = '1.118';

#-----------------------------------------------------------------------------

use Exception::Class (
    'Perl::Critic::Exception' => {
        isa         => 'Exception::Class::Base',
        description => 'A problem discovered by Perl::Critic.',
    },
);

use base 'Exporter';

#-----------------------------------------------------------------------------

sub short_class_name {
    my ( $self ) = @_;

    return substr ref $self, (length 'Perl::Critic') + 2;
}

#-----------------------------------------------------------------------------

1;

__END__

#-----------------------------------------------------------------------------

=pod

=for stopwords

=head1 NAME

Perl::Critic::Exception - A problem identified by L<Perl::Critic|Perl::Critic>.

=head1 DESCRIPTION

A base class for all problems discovered by
L<Perl::Critic|Perl::Critic>.  This exists to enable differentiating
exceptions from L<Perl::Critic|Perl::Critic> code from those
originating in other modules.

This is an abstract class.  It should never be instantiated.

=head1 INTERFACE SUPPORT

This is considered to be a public class.  Any changes to its interface
will go through a deprecation cycle.

=head1 METHODS

=over

=item C<short_class_name()>

Retrieve the name of the class of this object with C<'Perl::Critic::'>
stripped off.

=back

=head1 AUTHOR

Elliot Shank <perl@galumph.com>

=head1 COPYRIGHT

Copyright (c) 2007-2011 Elliot Shank.

This program is free software; you can redistribute it and/or modify
it under the same terms as Perl itself.  The full text of this license
can be found in the LICENSE file included with this module.

=cut

# Local Variables:
#   mode: cperl
#   cperl-indent-level: 4
#   fill-column: 78
#   indent-tabs-mode: nil
#   c-indentation-style: bsd
# End:
# ex: set ts=8 sts=4 sw=4 tw=78 ft=perl expandtab shiftround :


text:
<?php
/**
* @package Strider
* @author Ryan Rentfro & Isaac Mendoza
* @license MIT
*/
namespace Strider;

/**
 * The base Convert class
 */
class Convert
{
    /**
    * Converts a date to sql format and optionally converts a date based in seconds to a date first
    * @param string $date The date picker date or seconds that will be converted to the SQL date format.
    * @param boolean Flag that controls conversion of seconds to date.
    * @return string|boolean Returns SQL date if valid, returns false if invalid date.
    */
    public static function datepickerDatetoSQLDate($date, $secondsTodate = true)
    {
        if ($secondsTodate == true) $date = self::secondsToDate($date);
        if (strpos($date, '/') > 0)
        {
            $dateSeg = explode('/', $date);
            return $dateSeg['2'] . '-' . $dateSeg['0'] . '-' . $dateSeg['1'];
        }
        return false;
    }

    /**
    * Hashes value with halConfig::$salt
    * @param string $value The value to be hashed.
    * @return string The value plus salt hashed
    */
    public static function hashValue($value)
    {
        return md5($value . Config::$salt);
    }

    /**
    * Returns the string value of the scaled size of total bytes.
    * @param int $bytes Total bytes to be formatted.
    * @return string Largest size formatted byte string.
    */
    public static function formatSize($bytes)
    {
        $types = array( 'B', 'KB', 'MB', 'GB', 'TB' );
        for( $i = 0; $bytes >= 1024 && $i < ( count( $types ) -1 ); $bytes /= 1024, $i++ );
        return( round( $bytes, 2 ) . " " . $types[$i] );
    }

    /**
    * Produces the date for the seconds provided with optional declareable formatting.
    * @param int $seconds Seconds to be converted to date
    * @return string Seconds formatted into the supplied date format.
    */
    public static function secondsToDate($seconds, $format = 'm/d/Y')
    {
        return date($format, $seconds);
    }

    /**
    * Produces a "clean name" which means it lowercases, alphanumeris, and clears whitespace and replaces _ and " " with -
    * @param string $string The string that will be cleaned
    * @return string Returns a string with the provided string formatted as a "clean name"
    */
    public static function cleanName($string)
    {
        $string = strtolower($string);
        $string = preg_replace("/[^a-z0-9_\s-]/", "", $string);
        $string = preg_replace("/[\s-]+/", " ", $string);
        $string = preg_replace("/[\s_]/", "-", $string);
        return $string;
    }
}


text:
using Krystals5ObjectLibrary;

using Moritz.Globals;

using System.Diagnostics;
using System.Text;

namespace DeleteUnusedDuplicateKrystalsApp
{
    public partial class UtilitiesForm1 : Form
    {
        public UtilitiesForm1()
        {
            InitializeComponent();
        }

        #region DeleteUnusedDuplicateKrystals
        private void DeleteUnusedDuplicateKrystalsButton_Click(object sender, EventArgs e)
        {
            DialogResult result = MessageBox.Show("Delete all unused duplicate Krystals?\n\n" +
                "If unused duplicate krystals are found in the krystals\n" +
                "folder, a backup of that folder will first be created\n" +
                "in a new, parallel \"_MorizBackup\" folder.",
                "Delete Unused Duplicate Krystals", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning);

            if(result == DialogResult.OK)
            {
                List<string> filesToDelete = new List<string>();

                try
                {
                    Cursor.Current = Cursors.WaitCursor; // Note that the wait cursor is only displayed when over UtilitiesForm1

                    filesToDelete.AddRange(FindFilesToDelete(Directory.EnumerateFiles(_krystalsFolder, "*.constant.krys")));
                    filesToDelete.AddRange(FindFilesToDelete(Directory.EnumerateFiles(_krystalsFolder, "*.line.krys")));
                    filesToDelete.AddRange(FindFilesToDelete(Directory.EnumerateFiles(_krystalsFolder, "*.exp.krys")));
                    filesToDelete.AddRange(FindFilesToDelete(Directory.EnumerateFiles(_krystalsFolder, "*.mod.krys")));
                    filesToDelete.AddRange(FindFilesToDelete(Directory.EnumerateFiles(_krystalsFolder, "*.perm.krys")));
                    filesToDelete.AddRange(FindFilesToDelete(Directory.EnumerateFiles(_krystalsFolder, "*.path.krys")));
                }
                finally
                {
                    Cursor.Current = Cursors.Default;
                    StringBuilder msgStrB = new();
                    if(filesToDelete.Count == 0)
                    {
                        MessageBox.Show("No unused duplicate krystals were found", "Result", MessageBoxButtons.OK);
                    }
                    else
                    {
                        string backupDirectoryName = K.CopyDirectoryToMoritzBackup(_krystalsFolder);
                        msgStrB.Append("The following unused, duplicate krystals have been deleted:\n\n");
                        foreach(var filename in filesToDelete)
                        {
                            msgStrB.Append(filename + "\n");
                            var deletePath = _krystalsFolder + @"//" + filename;
                            File.Delete(deletePath);
                        }
                        msgStrB.Append($"\nA backup of the original krystals folder has been created in\n    {backupDirectoryName}");
                        MessageBox.Show(msgStrB.ToString(), "Deleted Krystals", MessageBoxButtons.OK);
                    }
                }
            }
        }

        private List<string> FindFilesToDelete(IEnumerable<string> iEnumKrystalPaths)
        {
            List<string> filesToDelete = new List<string>();

            if(iEnumKrystalPaths.Count<string>() > 1)
            {
                List<string> krystalPaths = iEnumKrystalPaths.ToList<string>();

                List<List<string>> listsOfDuplicates = GetListsOfDuplicates(krystalPaths);

                if(listsOfDuplicates.Count > 0 && listsOfDuplicates[0].Count > 0)
                {
                    // Now remove all krystalNames, from the listsOfDuplicates, that have children in the KrystalChildrenTreeView
                    Dictionary<string, List<string>> krystalScoresDict = K.GetKrystalScoresDict();

                    var krystalFamily = new KrystalFamily(this._krystalsFolder, krystalScoresDict);

                    var krystalChildrenTreeView = new KrystalChildrenTreeView(krystalFamily, null, null);

                    var rootNode = GetRootNode(krystalChildrenTreeView, listsOfDuplicates[0][0]);

                    foreach(var listOfDuplicates in listsOfDuplicates)
                    {
                        List<TreeNode> nodesToDelete = GetNodesToDelete(rootNode, listOfDuplicates);
                        foreach(var node in nodesToDelete)
                        {
                            string krystalPath = _krystalsFolder + "//" + node.Text;
                            filesToDelete.Add(node.Text);
                        }
                    }
                }
            }
            return filesToDelete;
        }

        private static List<TreeNode> GetNodesToDelete(TreeNode rootNode, List<string> listOfDuplicates)
        {
            List<TreeNode> rval = new List<TreeNode>();
            foreach(string krystalFilename in listOfDuplicates)
            {
                foreach(TreeNode node in rootNode.Nodes)
                {
                    if(node.Text == krystalFilename)
                    {
                        if(node.Nodes.Count == 0)
                        {
                            rval.Add(node);
                        }
                        break;
                    }
                }
            }
            if(rval.Count > 0)
            {
                rval.RemoveAt(rval.Count - 1); // the final duplicate is not deletable
            }
            return rval;
        }

        private TreeNode GetRootNode(KrystalChildrenTreeView krystalChildrenTreeView, string krystalFilename)
        {
            TreeNode rval = new();
            var krystalType = K.GetKrystalTypeFromKrystalName(krystalFilename);
            foreach(TreeNode node in krystalChildrenTreeView.Nodes)
            {
                if(node.Text == K.BrowserChildrenTreeViewRootNodeName(krystalType))
                {
                    rval = node;
                    break;
                }
            }

            return rval;
        }

        /// <summary>
        /// returns lists of filenames of duplicate krystals.
        /// Each list is in reverse order of index.
        /// </summary>
        /// <param name="allKrystalPaths"></param>
        /// <returns></returns>
        private List<List<string>> GetListsOfDuplicates(List<string> allKrystalPaths)
        {
            List<List<string>> allDuplicatesLists = new List<List<string>>();
            int allKrystalsCount = allKrystalPaths.Count();
            List<string> currentDuplicates = new List<string>();
            List<int> touchedKrystalIndices = new List<int>();

            for(int i = 0; i < allKrystalsCount; i++)
            {
                if(touchedKrystalIndices.Contains(i))
                {
                    continue;
                }
                else
                {
                    touchedKrystalIndices.Add(i);
                    var testKrystal = new DensityInputKrystal(allKrystalPaths[i]);
                    for(int j = i + 1; j < allKrystalsCount; j++)
                    {
                        if(touchedKrystalIndices.Contains(j))
                        {
                            continue;
                        }
                        else
                        {
                            var otherKrystal = new DensityInputKrystal(allKrystalPaths[j]);
                            if(testKrystal.Equals(otherKrystal)) // Equals only compares the strands in both krystals
                            {
                                if(currentDuplicates.Contains(testKrystal.Name) == false)
                                {
                                    if(currentDuplicates.Count > 0)
                                    {
                                        currentDuplicates.Sort(K.CompareKrystalNames);
                                        currentDuplicates.Reverse();
                                        allDuplicatesLists.Add(currentDuplicates);
                                    }
                                    currentDuplicates = new List<string>() { testKrystal.Name };
                                }
                                currentDuplicates.Add(otherKrystal.Name);
                                touchedKrystalIndices.Add(j);
                            }
                        }

                    }
                }
            }
            if(currentDuplicates.Count > 0)
            {
                allDuplicatesLists.Add(currentDuplicates);
            }

            return allDuplicatesLists;
        }

        #endregion

        #region Old SaveKrystalsWithNewNames
        /// <summary>
        /// 09.08.2022
        /// ACHTUNG: The following procedure was used to change the naming of existing krystals and expanders:
        /// Note step 4, and that any krystals not in the old backups will have to be saved separately.
        /// 1. copy the original files (having the original names) into the appropriate folders:
        ///    krystals/expansion operators
        ///    krystals/krystals
        ///    krystals/modulation operators
        /// 2. call this function, to create new files parallel to the old ones, and printing a table
        ///    of the oldName-newName equivalences to the console.
        ///    This info has been copied to krystals/NameChanges.txt
        /// 3. Manually delete the old files.
        /// 4. ACHTUNG: Manually change the remaining names of krystals and expanders inside expander (.kexp) files.
        /// 5. There was an incorrect schema location (beginning J:) in one of the Expanders.Change it manually.
        /// 6. Removed the temporary code in ModulationKrystal.cs.
        ///    See https://github.com/notator/Moritz/commit/407e635bd37f71c434a4b66988973fa5716016e4
        ///
        /// 12.09.2022 Added the initial automatic backup of the krystals folder, now that I have a function for that.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void SaveKrystalsWithNewNamesButton_Click(object sender, EventArgs e)
        {
            // 12.09.2022: These two lines added
            string backupDirectoryName = K.CopyDirectoryToMoritzBackup(_krystalsFolder);
            MessageBox.Show($"\nA backup of the original krystals folder has been created in\n    {backupDirectoryName}");

            Debug.Assert(false, "This function has only been kept for archiving purposes." +
                "Before running it, see the comment above it in the code.");

            Dictionary<string, string> expanderNamesDict = SaveExpandersWithNewNames();

            Console.WriteLine("=================================================");
            Console.WriteLine("Expander Name Changes");
            foreach(var pair in expanderNamesDict)
            {
                Console.WriteLine(pair.Key + " --> " + pair.Value);
            }

            var iEnumKrysFilePaths = Directory.EnumerateFiles(_krystalsFolder, "*.krys");

            List<string> krysFilePaths = iEnumKrysFilePaths.ToList();
            krysFilePaths.Sort();
            Dictionary<string, string> krystalNamesDict = SaveKrystalsWithNewNames(krysFilePaths, expanderNamesDict);

            Console.WriteLine("=================================================");
            Console.WriteLine("Krystal Name Changes");
            foreach(var pair in krystalNamesDict)
            {
                Console.WriteLine(pair.Key + " --> " + pair.Value);
            }
        }

        /// <summary>
        /// returns a dictionary of oldExpanderName, newExpanderName pairs.
        /// </summary>
        /// <returns></returns>
        private Dictionary<string, string> SaveExpandersWithNewNames()
        {
            var expandersNamesDict = new Dictionary<string, string>();
            var expanderFilePaths = Directory.EnumerateFiles(M.LocalMoritzExpansionFieldsFolder, "e*.kexp");
            List<string> sortedExpanderFilePaths = expanderFilePaths.ToList();
            sortedExpanderFilePaths.Sort();

            int index = 1;
            char[] dot = new char[] { '.' };
            foreach(string path in sortedExpanderFilePaths)
            {
                string oldName = Path.GetFileName(path);
                string bracketContent = oldName.Substring(oldName.IndexOf('(') + 1, oldName.IndexOf(')') - oldName.IndexOf('(') - 1);
                string[] content = bracketContent.Split(dot);
                string newName = String.Format($"{content[0]}.{content[1]}.{index}.kexp");
                index++;

                expandersNamesDict.Add(oldName, newName);

                string newPath = K.ExpansionOperatorsFolder + "//" + newName;
                File.Delete(newPath);
                File.Copy(path, newPath);
            }
            return expandersNamesDict;
        }

        private Dictionary<string, string> SaveKrystalsWithNewNames(List<string> krysFilePaths, Dictionary<string, string> expanderNamesDict)
        {
            Dictionary<string, string> rval = new Dictionary<string, string>();

            void SetRvalDict(string oldName, string newName)
            {
                if(!rval.ContainsKey(oldName))
                    rval.Add(oldName, newName);
            }

            string NewKrystalFilename(string oldName)
            {
                /// <summary>
                /// A Krystal's name root consists of its domain (=MaxValue) followed by a '.' character,
                ///   followed by a shapeNameString followed by a '.' character.
                /// The shapeNameString contains one or more integers separated by '_' characters.
                /// The first int in the shapeNameString is the number of level 1 and level 2 strands, so:
                ///  "0" is a constant krystal -- containing one strand having level 0 and one value (=domain) (no level 1 or level 2 strands).
                ///  "1_[nValues]" is a line krystal -- containing one strand having level 1 and [nValues] values (no level 2 strands).
                ///  "7_[nValues)" is a level 2 krystal -- containing 7 strands (1 level 1 and 6 level 2 strands) and [nValues] values.
                ///  "7_28_[nValues]" is a level 3 krystal - containing 28 strands having level 1, 2, or 3, and [nValues] values.
                ///  "7_28_206_[nValues]" is a level 4 krystal - containing 206 strands having level 1, 2, 3 or 4, and [nValues] values.
                /// </summary>
                /// <returns></returns>
                string GetNameRoot(Krystal k)
                {
                    StringBuilder sb = new StringBuilder();
                    sb.Append(k.MaxValue.ToString() + ".");

                    if(k.Level == 0)
                    {
                        sb.Append("0");
                    }
                    else if(k.Level == 1)
                    {
                        sb.Append("1");
                        sb.Append("_");
                        sb.Append(k.Strands[0].Values.Count().ToString());
                    }
                    else
                    {
                        for(int i = 1; i < k.ShapeArray.Length; i++)
                        {
                            sb.Append(k.ShapeArray[i].ToString() + '_');
                        }
                        sb.Remove(sb.Length - 1, 1);
                    }

                    sb.Append('.');

                    return sb.ToString();
                }

                string GetIndex(string name)
                {
                    StringBuilder sb = new StringBuilder();

                    int iInd = name.IndexOf("-");
                    int dotInd = name.LastIndexOf(".");
                    string iStr = name.Substring(iInd + 1, dotInd - iInd - 1);
                    int.TryParse(iStr, out int index);

                    sb.Append(index.ToString());
                    sb.Append('.');

                    return sb.ToString();
                }

                string NewExpandedKrystalName(Krystal k, int expanderID, K.KrystalType type)
                {
                    var nameRoot = GetNameRoot(k);
                    var index = GetIndex(k.Name);
                    string kName = String.Format($"{nameRoot}{expanderID}.{index}{type}.krys");

                    return kName;
                }

                string NewKrystalName(Krystal k, K.KrystalType type)
                {
                    var nameRoot = GetNameRoot(k);
                    var index = GetIndex(k.Name);
                    string kName = String.Format($"{nameRoot}{index}{type}.krys");

                    return kName;
                }

                int GetExpanderID(ExpansionKrystal k)
                {
                    string newEName = expanderNamesDict[k.ExpanderFilename];
                    char[] dot = new char[] { '.' };
                    string[] eComponents = newEName.Split(dot);
                    int.TryParse(eComponents[2], out int id);

                    return id;
                }

                string newName = "";
                if(rval.ContainsKey(oldName))
                {
                    newName = rval[oldName];
                }
                else
                {
                    int expanderID;
                    string typeString = oldName.Substring(0, 2);
                    switch(typeString)
                    {
                        case "ck":
                            var cKrystal = new ConstantKrystal(K.KrystalsFolder + "//" + oldName);
                            newName = cKrystal.Name;
                            break;
                        case "lk":
                            var lk = new LineKrystal(K.KrystalsFolder + "//" + oldName);
                            newName = NewKrystalName(lk, K.KrystalType.line);
                            break;
                        case "xk":
                            var xk = new ExpansionKrystal(K.KrystalsFolder + "//" + oldName);
                            expanderID = GetExpanderID(xk);
                            newName = NewExpandedKrystalName(xk, expanderID, K.KrystalType.exp);
                            break;
                        case "mk":
                            var mk = new ModulationKrystal(K.KrystalsFolder + "//" + oldName);
                            newName = NewKrystalName(mk, K.KrystalType.mod);
                            break;
                        case "pk":
                            var pk = new PermutationKrystal(K.KrystalsFolder + "//" + oldName);
                            newName = NewKrystalName(pk, K.KrystalType.perm);
                            break;
                    }
                }
                return newName;
            }

            foreach(var krysFilePath in krysFilePaths)
            {
                var originalKrysFilename = Path.GetFileName(krysFilePath);
                if(originalKrysFilename.StartsWith("ck"))
                {
                    ConstantKrystal cKrystal = new ConstantKrystal(krysFilePath);
                    string newCName = cKrystal.Name;
                    SetRvalDict(originalKrysFilename, newCName);
                    File.Delete(K.KrystalsFolder + "//" + newCName);
                    var hasBeenSaved = cKrystal.Save();
                    if(hasBeenSaved)
                    {
                        KrystalsBrowser kb = new KrystalsBrowser("New Krystal", cKrystal, null);
                        kb.Show();
                    }
                }
                if(originalKrysFilename.StartsWith("lk"))
                {
                    LineKrystal lKrystal = new LineKrystal(krysFilePath);
                    string newLName = NewKrystalFilename(lKrystal.Name);
                    lKrystal.Name = newLName;
                    SetRvalDict(originalKrysFilename, newLName);
                    File.Delete(K.KrystalsFolder + "//" + newLName);
                    var hasBeenSaved = lKrystal.Save();
                    if(hasBeenSaved)
                    {
                        KrystalsBrowser kb = new KrystalsBrowser("New Krystal", lKrystal, null);
                        kb.Show();
                    }
                }
                if(originalKrysFilename.StartsWith("xk"))
                {
                    ExpansionKrystal k = new ExpansionKrystal(krysFilePath);

                    string oldName = k.Name;
                    string newName = NewKrystalFilename(k.Name);
                    k.Name = newName;
                    SetRvalDict(oldName, newName);
                    string oldPInput = k.PointsInputFilename;
                    string newPInput = NewKrystalFilename(k.PointsInputFilename);
                    k.PointsInputFilename = newPInput;
                    SetRvalDict(oldPInput, newPInput);
                    string oldDInput = k.DensityInputFilename;
                    string newDInput = NewKrystalFilename(k.DensityInputFilename);
                    k.DensityInputFilename = newDInput;
                    SetRvalDict(oldDInput, newDInput);
                    string oldEName = k.ExpanderFilename;
                    string newEName = expanderNamesDict[oldEName];
                    k.ExpanderFilename = newEName;

                    File.Delete(K.KrystalsFolder + "//" + newName);

                    var hasBeenSaved = k.Save();
                    if(hasBeenSaved)
                    {
                        KrystalsBrowser kb = new KrystalsBrowser("New Krystal", k, null);
                        kb.Show();
                    }
                }
                if(originalKrysFilename.StartsWith("mk"))
                {
                    ModulationKrystal k = new ModulationKrystal(krysFilePath);
                    string oldName = k.Name;
                    string newName = NewKrystalFilename(k.Name);
                    k.Name = newName;
                    SetRvalDict(oldName, newName);
                    string oldXInput = k.XInputFilename;
                    string newXInput = NewKrystalFilename(k.XInputFilename);
                    k.XInputFilename = newXInput;
                    SetRvalDict(oldXInput, newXInput);
                    string oldYInput = k.YInputFilename;
                    string newYInput = NewKrystalFilename(k.YInputFilename);
                    k.YInputFilename = newYInput;
                    SetRvalDict(oldYInput, newYInput);

                    File.Delete(K.KrystalsFolder + "//" + newName);

                    var hasBeenSaved = k.Save();
                    if(hasBeenSaved)
                    {
                        KrystalsBrowser kb = new KrystalsBrowser("New Krystal", k, null);
                        kb.Show();
                    }
                }
                if(originalKrysFilename.StartsWith("pk"))
                {
                    PermutationKrystal k = new PermutationKrystal(krysFilePath);

                    string oldName = k.Name;
                    string newName = NewKrystalFilename(k.Name);
                    k.Name = newName;
                    SetRvalDict(oldName, newName);
                    string oldSInput = k.SourceInputFilename;
                    string newSInput = NewKrystalFilename(k.SourceInputFilename);
                    k.SourceInputFilename = newSInput;
                    SetRvalDict(oldSInput, newSInput);
                    string oldAInput = k.AxisInputFilename;
                    string newAInput = NewKrystalFilename(k.AxisInputFilename);
                    k.AxisInputFilename = newAInput;
                    SetRvalDict(oldAInput, newAInput);
                    string oldCName = k.ContourInputFilename;
                    string newCName = NewKrystalFilename(k.ContourInputFilename);
                    k.ContourInputFilename = newCName;
                    SetRvalDict(oldCName, newCName);

                    File.Delete(K.KrystalsFolder + "//" + newName);

                    var hasBeenSaved = k.Save();
                    if(hasBeenSaved)
                    {
                        KrystalsBrowser kb = new KrystalsBrowser("New Krystal", k, null);
                        kb.Show();
                    }
                }
            }

            return rval;
        }
        #endregion SaveKrystalsWithNewNames

        private void QuitButton_Click(object sender, EventArgs e)
        {
            M.Preferences.Dispose();
            Close();
        }

        private readonly string _krystalsFolder = M.LocalMoritzKrystalsFolder;
    }
}


text:
=============================
django-dynamic-preferences
=============================

.. image:: https://badge.fury.io/py/django-dynamic-preferences.png
    :target: https://badge.fury.io/py/django-dynamic-preferences

.. image:: https://readthedocs.org/projects/django-dynamic-preferences/badge/?version=latest
    :target: http://django-dynamic-preferences.readthedocs.org/en/latest/

.. image:: https://travis-ci.org/EliotBerriot/django-dynamic-preferences.svg?branch=master
    :target: https://travis-ci.org/EliotBerriot/django-dynamic-preferences

.. image:: https://travis-ci.org/EliotBerriot/django-dynamic-preferences.svg?branch=develop
    :target: https://travis-ci.org/EliotBerriot/django-dynamic-preferences

.. image:: https://img.shields.io/codecov/c/github/EliotBerriot/django-dynamic-preferences/master.svg
    :target: https://codecov.io/github/EliotBerriot/django-dynamic-preferences?branch=master

.. warning::

    There is a critical bug in version 1.2 that can result in dataloss. Please upgrade to 1.3 as
    soon as possible and do not use 1.2 in production. See `#81 <https://github.com/EliotBerriot/django-dynamic-preferences/pull/81>`_ for more details.

Dynamic-preferences is a Django app, BSD-licensed, designed to help you manage your project settings. While most of the time,
a `settings.py` file is sufficient, there are some situations where you need something more flexible such as:

* per-user settings (or, generally speaking, per instance settings)
* settings change without server restart

For per-instance settings, you could actually store them in some kind of profile model. However, it means that every time you want to add a new setting, you need to add a new column to the profile DB table. Not very efficient.

Dynamic-preferences allow you to register settings (a.k.a. preferences) in a declarative way. Preferences values are serialized before storage in database, and automatically deserialized when you need them.

With dynamic-preferences, you can update settings on the fly, through django's admin or custom forms, without restarting your application.

The project is tested and work under Python 2.7 and 3.4, 3.5 and 3.6, with django >=1.8.

Features
--------

* Simple to setup
* Admin integration
* Forms integration
* Bundled with global and per-user preferences
* Can be extended to other models if need (e.g. per-site preferences)
* Integrates with django caching mechanisms to improve performance

Documentation
-------------

The full documentation is at https://django-dynamic-preferences.readthedocs.org.

Contributing
------------

See http://django-dynamic-preferences.readthedocs.org/en/latest/contributing.html


text:
<?php

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

/* @var $this yii\web\View */
/* @var $model app\modules\auth\models\AuthUser */
/* @var $form yii\widgets\ActiveForm */
?>

    <?php $form = ActiveForm::begin(['enableClientValidation' => false]); ?>

    <?= $form->field($model, 'username')->textInput(['maxlength' => true]) ?>

    <?= $form->field($model, 'password')->passwordInput(['maxlength' => true]) ?>

    <?= $form->field($model, 'email')->textInput(['maxlength' => true]) ?>

        <?= Html::submitButton($model->isNewRecord ? 'Criar' : 'Salvar', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>

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

<?php
$script = <<< JS

 loading.turn.off('.loading-fog','.cssload-loader');

JS;

$this->registerJs($script,\yii\web\View::POS_LOAD);
?>


text:
// clang-format off

// clang-format on

#import <Firebase/Firebase.h>

#import "FirebaseTableViewDataSource.h"

@implementation FirebaseTableViewDataSource

#pragma mark -
#pragma mark FirebaseDataSource initializer methods

- (instancetype)initWithRef:(Firebase *)ref
        cellReuseIdentifier:(NSString *)identifier
                       view:(UITableView *)tableView {
  return [self initWithQuery:ref
                  modelClass:nil
                   cellClass:nil
         cellReuseIdentifier:identifier
                        view:tableView];
}

- (instancetype)initWithRef:(Firebase *)ref
   prototypeReuseIdentifier:(NSString *)identifier
                       view:(UITableView *)tableView {
  return [self initWithQuery:ref
                  modelClass:nil
                   cellClass:nil
         cellReuseIdentifier:identifier
                        view:tableView];
}

- (instancetype)initWithRef:(Firebase *)ref
                  cellClass:(Class)cell
        cellReuseIdentifier:(NSString *)identifier
                       view:(UITableView *)tableView {
  return [self initWithQuery:ref
                  modelClass:nil
                   cellClass:cell
         cellReuseIdentifier:identifier
                        view:tableView];
}

- (instancetype)initWithRef:(Firebase *)ref
                   nibNamed:(NSString *)nibName
        cellReuseIdentifier:(NSString *)identifier
                       view:(UITableView *)tableView {
  return [self initWithQuery:ref
                  modelClass:nil
                    nibNamed:nibName
         cellReuseIdentifier:identifier
                        view:tableView];
}

- (instancetype)initWithRef:(Firebase *)ref
                 modelClass:(Class)model
        cellReuseIdentifier:(NSString *)identifier
                       view:(UITableView *)tableView {
  return [self initWithQuery:ref
                  modelClass:model
                   cellClass:nil
         cellReuseIdentifier:identifier
                        view:tableView];
}

- (instancetype)initWithRef:(Firebase *)ref
                 modelClass:(Class)model
   prototypeReuseIdentifier:(NSString *)identifier
                       view:(UITableView *)tableView {
  return [self initWithQuery:ref
                  modelClass:model
                   cellClass:nil
         cellReuseIdentifier:identifier
                        view:tableView];
}

- (instancetype)initWithRef:(Firebase *)ref
                 modelClass:(Class)model
                  cellClass:(Class)cell
        cellReuseIdentifier:(NSString *)identifier
                       view:(UITableView *)tableView {
  return [self initWithQuery:ref
                  modelClass:model
                   cellClass:cell
         cellReuseIdentifier:identifier
                        view:tableView];
}

- (instancetype)initWithRef:(Firebase *)ref
                 modelClass:(Class)model
                   nibNamed:(NSString *)nibName
        cellReuseIdentifier:(NSString *)identifier
                       view:(UITableView *)tableView {
  return [self initWithQuery:ref
                  modelClass:model
                    nibNamed:nibName
         cellReuseIdentifier:identifier
                        view:tableView];
}

- (instancetype)initWithQuery:(FQuery *)query
          cellReuseIdentifier:(NSString *)identifier
                         view:(UITableView *)tableView {
  return [self initWithQuery:query
                  modelClass:nil
                   cellClass:nil
         cellReuseIdentifier:identifier
                        view:tableView];
}

- (instancetype)initWithQuery:(FQuery *)query
     prototypeReuseIdentifier:(NSString *)identifier
                         view:(UITableView *)tableView {
  self.hasPrototypeCell = YES;
  return [self initWithQuery:query
                  modelClass:nil
                   cellClass:nil
         cellReuseIdentifier:identifier
                        view:tableView];
}

- (instancetype)initWithQuery:(FQuery *)query
                    cellClass:(Class)cell
          cellReuseIdentifier:(NSString *)identifier
                         view:(UITableView *)tableView {
  return [self initWithQuery:query
                  modelClass:nil
                   cellClass:cell
         cellReuseIdentifier:identifier
                        view:tableView];
}

- (instancetype)initWithQuery:(FQuery *)query
                     nibNamed:(NSString *)nibName
          cellReuseIdentifier:(NSString *)identifier
                         view:(UITableView *)tableView {
  return [self initWithQuery:query
                  modelClass:nil
                    nibNamed:nibName
         cellReuseIdentifier:identifier
                        view:tableView];
}

- (instancetype)initWithQuery:(FQuery *)query
                   modelClass:(Class)model
          cellReuseIdentifier:(NSString *)identifier
                         view:(UITableView *)tableView {
  return [self initWithQuery:query
                  modelClass:model
                   cellClass:nil
         cellReuseIdentifier:identifier
                        view:tableView];
}

- (instancetype)initWithQuery:(FQuery *)query
                   modelClass:(Class)model
     prototypeReuseIdentifier:(NSString *)identifier
                         view:(UITableView *)tableView {
  self.hasPrototypeCell = YES;
  return [self initWithQuery:query
                  modelClass:model
                   cellClass:nil
         cellReuseIdentifier:identifier
                        view:tableView];
}

- (instancetype)initWithQuery:(FQuery *)query
                   modelClass:(Class)model
                    cellClass:(Class)cell
          cellReuseIdentifier:(NSString *)identifier
                         view:(UITableView *)tableView {
  FirebaseArray *array = [[FirebaseArray alloc] initWithQuery:query];
  self = [super initWithArray:array];
  if (self) {
    if (!model) {
      model = [FDataSnapshot class];
    }

    if (!cell) {
      cell = [UITableViewCell class];
    }

    self.tableView = tableView;
    self.modelClass = model;
    self.reuseIdentifier = identifier;
    self.populateCell = ^(id cell, id object) {
    };

    if (!self.hasPrototypeCell) {
      [self.tableView registerClass:cell forCellReuseIdentifier:self.reuseIdentifier];
    }
  }
  return self;
}

- (instancetype)initWithQuery:(FQuery *)query
                   modelClass:(Class)model
                     nibNamed:(NSString *)nibName
          cellReuseIdentifier:(NSString *)identifier
                         view:(UITableView *)tableView {
  FirebaseArray *array = [[FirebaseArray alloc] initWithQuery:query];
  self = [super initWithArray:array];
  if (self) {
    if (!model) {
      model = [FDataSnapshot class];
    }

    self.tableView = tableView;
    self.modelClass = model;
    self.reuseIdentifier = identifier;
    self.populateCell = ^(id cell, id object) {
    };

    if (!self.hasPrototypeCell) {
      UINib *nib = [UINib nibWithNibName:nibName bundle:nil];
      [self.tableView registerNib:nib forCellReuseIdentifier:self.reuseIdentifier];
    }
  }
  return self;
}

#pragma mark -
#pragma mark FirebaseCollectionDelegate methods

- (void)childAdded:(id)obj atIndex:(NSUInteger)index {
  [self.tableView beginUpdates];
  [self.tableView insertRowsAtIndexPaths:@[ [NSIndexPath indexPathForRow:index inSection:0] ]
                        withRowAnimation:UITableViewRowAnimationAutomatic];
  [self.tableView endUpdates];
}

- (void)childChanged:(id)obj atIndex:(NSUInteger)index {
  [self.tableView beginUpdates];
  [self.tableView reloadRowsAtIndexPaths:@[ [NSIndexPath indexPathForRow:index inSection:0] ]
                        withRowAnimation:UITableViewRowAnimationAutomatic];
  [self.tableView endUpdates];
}

- (void)childRemoved:(id)obj atIndex:(NSUInteger)index {
  [self.tableView beginUpdates];
  [self.tableView deleteRowsAtIndexPaths:@[ [NSIndexPath indexPathForRow:index inSection:0] ]
                        withRowAnimation:UITableViewRowAnimationAutomatic];
  [self.tableView endUpdates];
}

- (void)childMoved:(id)obj fromIndex:(NSUInteger)fromIndex toIndex:(NSUInteger)toIndex {
  [self.tableView beginUpdates];
  [self.tableView moveRowAtIndexPath:[NSIndexPath indexPathForRow:fromIndex inSection:0]
                         toIndexPath:[NSIndexPath indexPathForRow:toIndex inSection:0]];
  [self.tableView endUpdates];
}

#pragma mark -
#pragma mark UITableViewDataSource methods

- (id)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
  id cell = [self.tableView dequeueReusableCellWithIdentifier:self.reuseIdentifier
                                                 forIndexPath:indexPath];

  FDataSnapshot *snap = [self.array objectAtIndex:indexPath.row];
  if (![self.modelClass isSubclassOfClass:[FDataSnapshot class]]) {
    id model = [[self.modelClass alloc] init];
    // TODO: replace setValuesForKeysWithDictionary with client API
    // valueAsObject method
    [model setValuesForKeysWithDictionary:snap.value];
    self.populateCell(cell, model);
  } else {
    self.populateCell(cell, snap);
  }

  return cell;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
  return [self.array count];
}

- (void)populateCellWithBlock:(__NON_NULL void (^)(__KINDOF(UITableViewCell)__NON_NULL_PTR cell,
                                                   __KINDOF(NSObject)
                                                       __NON_NULL_PTR object))callback {
  self.populateCell = callback;
}

@end


text:
            About

            Contact

            Twitter

            Github

          {% include svg/logo.svg %}

      {% if page.path contains "_posts" %}

      {% else %}

        {{ site.title }}

        {{ site.subtitle }}

      {% endif %}