text:
#include "gameTime.h"

#include "saiga/core/math/math.h"

#include "internal/noGraphicsAPI.h"

namespace Saiga
{
GameTime gameTime;

void GameTime::init(tick_t _dt, tick_t _dtr)
{
    maxGameLoopDelay = std::chrono::duration_cast<tick_t>(std::chrono::hours(1000));
    dt               = _dt;
    dtr              = _dtr;

    gameTimer.start();

    realTime     = gameTimer.stop();
    lastRealTime = realTime;

    update();
    nextUpdateTime = scaledTime;
}

double GameTime::getTimeScale() const
{
    return timeScale;
}

void GameTime::setTimeScale(double value)
{
    timeScale = value;
}

void GameTime::jumpToLive()
{
    jtl = true;
}

void GameTime::update()
{
    realTime        = gameTimer.stop();
    auto step       = realTime - lastRealTime;
    auto scaledStep = std::chrono::duration_cast<tick_t>(step * timeScale);
    scaledTime += scaledStep;
    lastRealTime = realTime;
}

bool GameTime::shouldUpdate()
{
    update();
    auto currentDelay = scaledTime - nextUpdateTime;

    if (currentDelay > maxGameLoopDelay)
    {
        jtl = true;
    }

    if (jtl)
    {
        if (currentDelay.count() > 0)
        {
            if (printInfoMsg)
            {
                //                std::cout << "> Advancing game time to live. Adding a delay of " <<
                //                std::chrono::duration_cast<std::chrono::duration<double,std::milli>>(currentDelay).count()
                //                << " ms" << std::endl;
            }
            scaledTime    = nextUpdateTime;
            nextFrameTime = realTime;
        }
        jtl = false;
    }

    if (currentDelay > tick_t(0))
    {
        actualUpdateTime = scaledTime;
        updatetime       = nextUpdateTime;
        currentTime      = updatetime;
        nextUpdateTime += dt;
        return true;
    }
    else
    {
        return false;
    }
}

bool GameTime::shouldRender()
{
    update();
    if (realTime > nextFrameTime)
    {
        //        updatetime = nextFrameTick;

        tick_t ticksSinceLastUpdate = scaledTime - actualUpdateTime;

        renderTime  = updatetime + ticksSinceLastUpdate;
        currentTime = renderTime;

        //        calculate the interpolation value. Useful when the framerate is higher than the update rate
        interpolation = (double)ticksSinceLastUpdate.count() / (nextUpdateTime - updatetime).count();
        interpolation = clamp(interpolation, 0.0, 1.0);

        nextFrameTime += dtr;
        return true;
    }
    else
    {
        return false;
    }
}

tick_t GameTime::getSleepTime()
{
    update();

    auto timeTillU = nextUpdateTime - scaledTime;
    auto timeTillR = nextFrameTime - realTime;

    tick_t nextEvent = timeTillU < timeTillR ? timeTillU : timeTillR;
    return nextEvent;
}

}  // namespace Saiga


text:
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
  <component name="ProjectModuleManager">
    <modules>
      <module fileurl="file://$PROJECT_DIR$/.idea/mongodb-driver-2.0.iml" filepath="$PROJECT_DIR$/.idea/mongodb-driver-2.0.iml" />
    </modules>
  </component>
</project>

redpajama_set_name: RedPajamaGithub


text:
pub(crate) mod flat;

use std::{
    io::{self, BufRead, Write},
    path::PathBuf,
};

use serde::{de::DeserializeOwned, Deserialize, Serialize};

use crate::ProcMacroKind;

pub use crate::msg::flat::FlatTree;

#[derive(Debug, Serialize, Deserialize)]
pub enum Request {
    ListMacros { dylib_path: PathBuf },
    ExpandMacro(ExpandMacro),
}

#[derive(Debug, Serialize, Deserialize)]
pub enum Response {
    ListMacros(Result<Vec<(String, ProcMacroKind)>, String>),
    ExpandMacro(Result<FlatTree, PanicMessage>),
}

#[derive(Debug, Serialize, Deserialize)]
pub struct PanicMessage(pub String);

#[derive(Debug, Serialize, Deserialize)]
pub struct ExpandMacro {
    /// Argument of macro call.
    ///
    /// In custom derive this will be a struct or enum; in attribute-like macro - underlying
    /// item; in function-like macro - the macro body.
    pub macro_body: FlatTree,

    /// Name of macro to expand.
    ///
    /// In custom derive this is the name of the derived trait (`Serialize`, `Getters`, etc.).
    /// In attribute-like and function-like macros - single name of macro itself (`show_streams`).
    pub macro_name: String,

    /// Possible attributes for the attribute-like macros.
    pub attributes: Option<FlatTree>,

    pub lib: PathBuf,

    /// Environment variables to set during macro expansion.
    pub env: Vec<(String, String)>,

    pub current_dir: Option<String>,
}

pub trait Message: Serialize + DeserializeOwned {
    fn read(inp: &mut impl BufRead, buf: &mut String) -> io::Result<Option<Self>> {
        Ok(match read_json(inp, buf)? {
            None => None,
            Some(text) => {
                let mut deserializer = serde_json::Deserializer::from_str(text);
                // Note that some proc-macro generate very deep syntax tree
                // We have to disable the current limit of serde here
                deserializer.disable_recursion_limit();
                Some(Self::deserialize(&mut deserializer)?)
            }
        })
    }
    fn write(self, out: &mut impl Write) -> io::Result<()> {
        let text = serde_json::to_string(&self)?;
        write_json(out, &text)
    }
}

impl Message for Request {}
impl Message for Response {}

fn read_json<'a>(inp: &mut impl BufRead, buf: &'a mut String) -> io::Result<Option<&'a String>> {
    loop {
        buf.clear();

        inp.read_line(buf)?;
        buf.pop(); // Remove trailing '\n'

        if buf.is_empty() {
            return Ok(None);
        }

        // Some ill behaved macro try to use stdout for debugging
        // We ignore it here
        if !buf.starts_with('{') {
            tracing::error!("proc-macro tried to print : {}", buf);
            continue;
        }

        return Ok(Some(buf));
    }
}

fn write_json(out: &mut impl Write, msg: &str) -> io::Result<()> {
    tracing::debug!("> {}", msg);
    out.write_all(msg.as_bytes())?;
    out.write_all(b"\n")?;
    out.flush()?;
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use tt::*;

    fn fixture_token_tree() -> Subtree {
        let mut subtree = Subtree::default();
        subtree
            .token_trees
            .push(TokenTree::Leaf(Ident { text: "struct".into(), id: TokenId(0) }.into()));
        subtree
            .token_trees
            .push(TokenTree::Leaf(Ident { text: "Foo".into(), id: TokenId(1) }.into()));
        subtree.token_trees.push(TokenTree::Leaf(Leaf::Literal(Literal {
            text: "Foo".into(),
            id: TokenId::unspecified(),
        })));
        subtree.token_trees.push(TokenTree::Leaf(Leaf::Punct(Punct {
            char: '@',
            id: TokenId::unspecified(),
            spacing: Spacing::Joint,
        })));
        subtree.token_trees.push(TokenTree::Subtree(Subtree {
            delimiter: Some(Delimiter { id: TokenId(2), kind: DelimiterKind::Brace }),
            token_trees: vec![],
        }));
        subtree
    }

    #[test]
    fn test_proc_macro_rpc_works() {
        let tt = fixture_token_tree();
        let task = ExpandMacro {
            macro_body: FlatTree::new(&tt),
            macro_name: Default::default(),
            attributes: None,
            lib: std::env::current_dir().unwrap(),
            env: Default::default(),
            current_dir: Default::default(),
        };

        let json = serde_json::to_string(&task).unwrap();
        // println!("{}", json);
        let back: ExpandMacro = serde_json::from_str(&json).unwrap();

        assert_eq!(tt, back.macro_body.to_subtree());
    }
}


text:
package strategy

import (
	"io/ioutil"

	kapi "github.com/GoogleCloudPlatform/kubernetes/pkg/api"
	"github.com/GoogleCloudPlatform/kubernetes/pkg/runtime"

	buildapi "github.com/openshift/origin/pkg/build/api"
)

// STIBuildStrategy creates STI(source to image) builds
type STIBuildStrategy struct {
	Image                string
	TempDirectoryCreator TempDirectoryCreator
	UseLocalImages       bool
	// Codec is the codec to use for encoding the output pod.
	// IMPORTANT: This may break backwards compatibility when
	// it changes.
	Codec runtime.Codec
}

type TempDirectoryCreator interface {
	CreateTempDirectory() (string, error)
}

type tempDirectoryCreator struct{}

func (tc *tempDirectoryCreator) CreateTempDirectory() (string, error) {
	return ioutil.TempDir("", "stibuild")
}

var STITempDirectoryCreator = &tempDirectoryCreator{}

// CreateBuildPod creates a pod that will execute the STI build
// TODO: Make the Pod definition configurable
func (bs *STIBuildStrategy) CreateBuildPod(build *buildapi.Build) (*kapi.Pod, error) {
	data, err := bs.Codec.Encode(build)
	if err != nil {
		return nil, err
	}
	pod := &kapi.Pod{
		ObjectMeta: kapi.ObjectMeta{
			Name: build.PodName,
		},
		Spec: kapi.PodSpec{
			Containers: []kapi.Container{
				{
					Name:  "sti-build",
					Image: bs.Image,
					Env: []kapi.EnvVar{
						{Name: "BUILD", Value: string(data)},
					},
					// TODO: run unprivileged https://github.com/openshift/origin/issues/662
					Privileged: true,
				},
			},
			RestartPolicy: kapi.RestartPolicy{
				Never: &kapi.RestartPolicyNever{},
			},
		},
	}

	if bs.UseLocalImages {
		pod.Spec.Containers[0].ImagePullPolicy = kapi.PullIfNotPresent
	}

	setupDockerSocket(pod)
	setupDockerConfig(pod)
	return pod, nil
}


text:
import { module, test } from 'qunit';
import { setupTest } from 'ember-qunit';

module('Unit | Model | Report', function (hooks) {
  setupTest(hooks);

  test('it exists', function (assert) {
    const model = this.owner.lookup('service:store').createRecord('report');
    assert.ok(!!model);
  });
});


text:
import argparse
import os
import signal
import sys
import time

import rtmidi

def signal_handler(signal, frame):
    """Handler for Ctrl-C"""
    sys.exit(0)

def midi_in_callback(value, args):
    """Function called when MIDI data is received"""
    data = value[0]
    if args.hex:
        print('[' + ', '.join('0x%02X' % x for x in data) + ']')
    else:
        print(data)

def get_port(client, device_id):
    """Return open port for a device"""
    try:
        # Try to parse device id as number first
        dev_id = int(device_id)
        if not dev_id < len(client.get_ports()):
            raise Exception('Device id out of range')
    except ValueError:
        # If this fails, try to find a port name starting with it
        for i, name in enumerate(client.get_ports()):
            if name.lower().startswith(device_id.lower()):
                return client.open_port(i)
        # If this also fails, try to find a port name that contains
        # a substring of it
        for i, name in enumerate(client.get_ports()):
            if device_id.lower() in name.lower():
                return client.open_port(i)
        raise Exception('Device "%s" not found' % device_id)

    return client.open_port(dev_id)

def main():
    if len(sys.argv) < 2:
        # Show help when no arguments are given
        sys.argv.append('-h')

    # Setup command line parser
    parser = argparse.ArgumentParser(description='MIDI utility')
    parser.add_argument('-l', '--list', action='store_true',
                        help='List connected devices')
    parser.add_argument('-d', '--device', metavar='ID',
                        help='Selected device')
    parser.add_argument('-w', '--write', type=str, nargs='+', metavar='DATA',
                        help='Write data')
    parser.add_argument('-r', '--read', action='store_true',
                        help='Read data')
    parser.add_argument('-x', '--hex', action='store_true',
                        help='Show/interprete data as hex')
    parser.add_argument('-s', '--sysex-file', metavar='FILE',
                        help='Sysex file to transmit')
    args = parser.parse_args()

    try:
        if args.list:
            # List command, show all connected devices
            print()
            print('Available ports:')
            print()
            print('\tInput:')
            print('\t', 'ID', 'Name', sep='\t')
            for i, name in enumerate(rtmidi.MidiIn().get_ports()):
                print('\t', i, name, sep='\t')
            print()
            print('\tOutput:')
            print('\t', 'ID', 'Name', sep='\t')
            for i, name in enumerate(rtmidi.MidiOut().get_ports()):
                print('\t', i, name, sep='\t')
            print()

        elif args.write:
            # Write command, send data
            if not args.device:
                raise Exception('No device specified.')
            outport = get_port(rtmidi.MidiOut(), args.device)
            if args.hex:
                data = [int(x, 16) for x in args.write]
            else:
                data = [int(x, 0) for x in args.write]
            outport.send_message(data)
            del outport

        elif args.read:
            # Read command, receive data until Ctrl-C is pressed
            signal.signal(signal.SIGINT, signal_handler)
            if not args.device:
                raise Exception('No device specified.')
            inport = get_port(rtmidi.MidiIn(), args.device)
            inport.set_callback(midi_in_callback, args)
            inport.ignore_types(False, False, False)
            while True:
                time.sleep(1)

        elif args.sysex_file:
            # Send sysex file command
            if not args.device:
                raise Exception('No device specified.')
            outport = get_port(rtmidi.MidiOut(), args.device)
            file_path = args.sysex_file
            if not (os.path.exists(file_path) and os.path.isfile(file_path)):
                raise Exception('File "%s" does not exist.' % file_path)
            with open(file_path, "rb") as f:
                data = f.read()
                data_pos = 0
                while True:
                    sysex_start_pos = data.find(b"\xF0", data_pos)
                    sysex_end_pos = data.find(b"\xF7", data_pos)
                    if sysex_start_pos >= 0 and sysex_end_pos >= 0:
                        message = data[sysex_start_pos:sysex_end_pos + 1]
                        print("Sending sysex message with %i bytes." %
                              len(message))
                        outport.send_message(message)
                        time.sleep(0.05)
                        data_pos = sysex_end_pos + 1
                    else:
                        break

    except Exception as e:
        print('Error:', e)

if __name__ == '__main__':
    main()


text:
package org.apache.felix.dm.itest.api;

import org.junit.Assert;

import org.apache.felix.dm.Component;
import org.apache.felix.dm.DependencyManager;
import org.apache.felix.dm.ServiceDependency;
import org.apache.felix.dm.itest.util.Ensure;
import org.apache.felix.dm.itest.util.TestBase;

/**
 * This testcase verify that a Service is not started if one of its extra required dependencies
 * is unavailable.
 *
 * @author Felix Project Team
 */
public class FELIX2369_ExtraDependencyTest extends TestBase
{
    public void testExtraDependencies() {
        DependencyManager m = getDM();
        // helper class that ensures certain steps get executed in sequence
        Ensure e = new Ensure();
        // create a service consumer and provider
        Component sp1 = m.createComponent().setInterface(MyService1.class.getName(), null).setImplementation(new MyService1Impl());
        Component sc = m.createComponent().setImplementation(new MyClient(e, 1));

        // provides the MyService1 service (but not the MyService2, which is required by MyClient).
        m.add(sp1);
        // add MyClient (it should not be invoked in its start() method because MyService2 is not there
        m.add(sc);
        // remove MyClient (it should not be invoked in its stop() method because it should not be active, since MyService2 is not there.
        m.remove(sc);
        e.waitForStep(2, 5000);
        m.clear();
    }

    public interface MyService1 {
    }

    public interface MyService2 {
    }

    public static class MyService1Impl implements MyService1 {
    }

    public static class MyService2Impl implements MyService2 {
    }

    // This client is not using callbacks, but instead, it uses auto config.
    public static class MyClient {
        MyService1 m_myService2; // required/unavailable
        private Ensure m_ensure;
        private final int m_startStep;

        public MyClient(Ensure e, int startStep) {
            m_ensure = e;
            m_startStep = startStep;
        }

        public void init(Component s) {
            DependencyManager dm = s.getDependencyManager();
            m_ensure.step(m_startStep);
            ServiceDependency d1 =
                    dm.createServiceDependency() // this dependency is available at this point
                      .setService(MyService1.class)
                      .setRequired(false)
                      .setCallbacks("bind", null);
            ServiceDependency d2 =
            		dm.createServiceDependency() // not available: we should not be started
                      .setService(MyService2.class)
                      .setRequired(true)
                      .setAutoConfig("m_myService2");

            s.add(d1, d2); // atomically add these two dependencies
        }

        public void start() {
            Assert.fail("start should not be called since MyService2 is unavailable");
        }

        void bind(MyService1 s1) { // optional/available
            System.out.println("bound MyService1");
        }

        public void stop() {
            Assert.fail("stop should not be called since we should not be active at this point");
        }

        public void destroy() {
            m_ensure.step(m_startStep+1);
        }
    }
}


text:
var fs = require('fs'),
    Promise = require('promise');

var cloudant_client = {
    defaults: {
        ww_binding_user_doc_id: "ww_binding_user",
    },
    credentials: {
        dbName: "ww_scratchpad",
    },
    connection: {},
};

cloudant_client.getDBCredentialsUrl = function(jsonData) {
    var vcapServices = JSON.parse(jsonData);
    // Pattern match to find the first instance of a Cloudant service in
    // VCAP_SERVICES. If you know your service key, you can access the
    // service credentials directly by using the vcapServices object.
    for (var vcapService in vcapServices) {
        if (vcapService.match(/cloudant/i)) {
            return vcapServices[vcapService][0].credentials.url;
        }
    }
}

cloudant_client.initDBConnection = function() {
    //When running on Bluemix, this variable will be set to a json object
    //containing all the service credentials of all the bound services
    if (process.env.VCAP_SERVICES) {
        this.credentials.url = this.getDBCredentialsUrl(process.env.VCAP_SERVICES);
    } else { //When running locally, the VCAP_SERVICES will not be set

        // When running this app locally you can get your Cloudant credentials
        // from Bluemix (VCAP_SERVICES in "cf env" output or the Environment
        // Variables section for an app in the Bluemix console dashboard).
        // Once you have the credentials, paste them into a file called vcap-local.json.
        // Alternately you could point to a local database here instead of a
        // Bluemix service.
        // url will be in this format: https://username:password@xxxxxxxxx-bluemix.cloudant.com
         this.credentials.url = this.getDBCredentialsUrl(fs.readFileSync("hyarthi-scratchpad_vcap.json", "utf-8"));
    }

    this.connection = require('cloudant')(this.credentials.url);

    // check if DB exists if not create
    this.connection.db.create(this.credentials.dbName, function(err, res) {
        if (err) {
            console.log('Could not create new db: ' + cloudant_client.credentials.dbName + ', it might already exist.');
        }
    });

    this.db = this.connection.use(this.credentials.dbName);
}

cloudant_client.initDBConnection();

cloudant_client.getWWCredentials = function(callback) {
    if(this.db !== null) {
        console.log('Querying Couch/Cloudant...');
        return new Promise((resolve, reject) => {
            this.db.get('ww_app_id', (err, body) => {
                if (err) {
                    console.log('Error: ' + err);
                    reject(err);
                }
                resolve(body);
            });
        });
        //this.db.get('ww_app_id', callback);
    } else {
        console.log('Could not get WW credentials - no DB connection');
        return new Promise((resolve, reject) => {
            reject(new Error('Could not get WW credentials - no DB connection'));
        });
    }
};

cloudant_client.getSpaceDoc = function(id) {
    if (this.db !== null) {
        console.log('>>> Getting space doc...');
        return new Promise((resolve, reject) => {
            cloudant_client.db.get(cloudant_client.parseDocId(id, 'SPC'), function (err, body) {
                if (err) {
                    console.log('error - ' + err);
                    // does not exist?
                    resolve(null);
                } else {
                    console.log('resolving body...');
                    resolve(body);
                }
            });
        });
    } else {
        console.log('Could not get space doc - no DB connection');
        return new Promise((resolve, reject) => {
            reject(new Error('Could not get space doc - no DB connection'));
        });
    }
};

cloudant_client.updateMessageDoc = function (doc) {
    if (this.db !== null) {
        console.log('>>> Updating message doc...');
        return new Promise((resolve, reject) => {
            cloudant_client.db.get(cloudant_client.parseDocId(doc.id, 'MSG'), function (err, body) {
                var indoc = {
                    _id: cloudant_client.parseDocId(doc.id, 'MSG'),
                    spaceId: cloudant_client.parseDocId(doc.spaceId, 'SPC'),
                    content: doc.content,
                    contentType: doc.contentType,
                    created: new Date(doc.created),
                    updated: new Date(doc.updated)
                };
                if (!err)
                    indoc._rev = body._rev; // exists -> update
                else
                    console.log("error - " + err);  // doesn't exist -> insert
                if (doc.createdBy && doc.createdBy.id) {
                    indoc.createdBy = cloudant_client.parseDocId(doc.createdBy.id, 'USR');
                } else {
                    indoc.createdBy = null;
                }
                if (doc.updatedBy && doc.updatedBy.id) {
                    indoc.updatedBy = cloudant_client.parseDocId(doc.updatedBy.id, 'USR');
                }
                cloudant_client.db.insert(indoc, (er, bdy) => {
                    if (er) {
                        console.log('error - ' + er);
                        resolve(false);
                        // does not exist?
                    } else {
                        console.log("------> success: " + JSON.stringify(bdy));
                        // insert annotation docs
                        console.log("---> starting to insert annotation docs...");
                        var annos = [];
                        if (doc.annotations)
                            for (var i = 0; i < doc.annotations.length; i++) {
                                var item = JSON.parse(doc.annotations[i]);
                                item.spaceId = cloudant_client.parseDocId(doc.spaceId, 'SPC');
                                item.msgId = cloudant_client.parseDocId(doc.id, 'MSG');
                                // fix dates
                                cloudant_client._fixAnnoDates(item);
                                annos[i] = cloudant_client.updateAnnotationDoc(item);
                            }
                        Promise.all(annos).then(results => {
                            //console.log('anno update results: ' + annos);
                            if (results.indexOf(false) < 0) {
                                console.log('no errors in annos!');
                                resolve(true);
                            } else {
                                console.log('caught errors in anno!');
                                resolve(false);
                            }
                        });
                        //resolve(true);
                    }
                });
            });
        });
    } else {
        console.log('Could not update message doc - no DB connection');
        return new Promise((resolve) => {
            resolve(false);
        });
    }
};

cloudant_client._fixAnnoDates = function (anno) {
    //console.log();
    //console.log("checking for created(" + typeof anno.created + ")");
    if (anno.created && typeof anno.created === 'number') {
        anno.created = new Date(anno.created);
    }
    //console.log("checking for updated(" + typeof anno.updated + ")");
    //console.log();
    if (anno.updated && typeof anno.updated === 'number') {
        anno.updated = new Date(anno.updated);
    }
};

cloudant_client.updateAnnotationDoc = function (doc) {
    //console.log("STUB: " + JSON.stringify(doc));
    if (this.db !== null) {
        console.log("Updating annotation doc...");
        return new Promise((resolve, reject) => {
            console.log("checking annotation with id " + doc.annotationId);
            cloudant_client.db.get(cloudant_client.parseDocId(doc.annotationId, 'ANT'), (err, body) => {
                //console.log("BING!");
                doc._id = cloudant_client.parseDocId(doc.annotationId, 'ANT');
                if (!err)
                    doc._rev = body._rev;
                else
                    console.log('anno error - ' + err);
                cloudant_client.db.insert(doc, (er, bdy) => {
                    if (er) {
                        console.log('anno insert error - ' + er);
                        resolve(false);
                    } else {
                        console.log("------> success: " + JSON.stringify(bdy));
                        resolve(true);
                    }
                });
            });
        });
    } else {
        console.log('Could not update message doc - no DB connection');
        return new Promise((resolve) => {
            resolve(false);
        });
    }
};

cloudant_client.updateMemberDoc = function (doc) {
    return new Promise(resolve => {
        if (cloudant_client.db === null) {
            console.log('Could not update member doc - no DB connection');
            resolve (false);
        }
        console.log("Updating member doc...");
       // console.log('checking');
        cloudant_client.db.get(cloudant_client.parseDocId(doc.id, 'USR'), (err, body) => {
            doc._id = cloudant_client.parseDocId(doc.id, 'USR');
            if (!err)
                doc._rev = body._rev;
            else
                console.log('member error - ' + err);
            cloudant_client.db.insert(doc, (er, bdy) => {
                if (er) {
                    console.log('member insert error - ' + er);
                    resolve(false);
                } else {
                    console.log("------> success: " + JSON.stringify(bdy));
                    resolve(true);
                }
            });
        });
    });
};

cloudant_client.updateSpaceDoc = function (doc) {
    return new Promise(resolve => {
        if (cloudant_client.db === null) {
            console.log('Could not update space doc - no DB connection');
            resolve (false);
        }
        console.log("Updating space doc...");
        cloudant_client.db.get(cloudant_client.parseDocId(doc.id, 'SPC'), (err, body) => {
            doc._id = cloudant_client.parseDocId(doc.id, 'SPC');
            if (!err)
                doc._rev = body._rev;
            else
                console.log("space error - " + err);
            delete doc.status;
            cloudant_client.db.insert(doc, (er, bdy) => {
                if (er) {
                    console.log('space insert error - ' + er);
                    resolve(false);
                } else {
                    console.log("------> success: " + JSON.stringify(bdy));
                    resolve(true);
                }
            });
        });
    });
}

cloudant_client.getMessageDoc = function (id) {
    return new Promise((resolve, reject) => {
            //console.log("promise 1");
            cloudant_client.db.get(cloudant_client.parseDocId(doc.id, 'MSG'), function (err, body) {
                if (err) {
                    console.log('error - ' + err);
                    resolve(null);
                } else {
                    console.log("check body: " + JSON.stringify(body));
                    resolve(body);
                }
            });
        });
};

cloudant_client.parseDocId = function (id, type) {
    var prefix = "";
    switch(type) {
        case 'MSG':
            prefix = "msg_";
            break;
        case 'USR':
            prefix = "usr_";
            break;
        case 'ANT':
            prefix = "ant_";
            break;
        case 'SPC':
            prefix = "spc_";
            break;
        default:
            console.log("WARNING: Unrecognized type (" + type + ")");
            break;
    }
    return id.startsWith(prefix) ? id : prefix + id;
};

cloudant_client.getAnnotations = function(spaceId, start, limit) {
    let skp = (start ? start : 0);
    let lst = (limit ? limit : 100);
    return new Promise((resolve, reject) => {
        cloudant_client.db.find(
            {
                selector: {
                    _id: {
                        '$regex': "^ant_*"
                    },
                    spaceId: cloudant_client.parseDocId(spaceId, 'SPC'),
                },
                limit: lst,
                skip: skp
            },
            (err, result) => {
                if (err) {
                    console.log("ERROR: ---> " + err);
                    reject(err);
                }

                resolve(result.docs);
            },
        );
    });
}

cloudant_client.getMoments = function(spaceId, start, limit) {
    let skp = (start ? start : 0);
    let lst = (limit ? limit : 100);
   // console.log('>>>>> query cloudant');
    return new Promise((resolve, reject) => {
        //try {
            cloudant_client.db.find(
                {
                    selector: {
                        _id: {
                            '$regex': "^ant_*"
                        },
                        spaceId: cloudant_client.parseDocId(spaceId, 'SPC'),
                        momentId: {
                            '$gt': null
                        }
                    },
                    limit: lst,
                    skip: skp
                },
                (err, result) => {
                    //console.log("err: " + JSON.stringify(err));
                    //console.log("result: " + JSON.stringify(result));
                    if (err) {
                        console.log("ERROR: ---> " + err);
                        reject(err);
                    }
                    //console.log('got docs: ' + JSON.stringify(result.docs));
                    resolve(result.docs);
                },
            );
        /*} catch (e) {
            console.log("ERR: " + e);
            reject(e);
        }*/
    });
}

cloudant_client.getMessagesBetween = function(spaceId, startDate, endDate, start, limit) {
    let skp = (start ? start : 0);
    let lst = (limit ? limit : 100);
     return new Promise((resolve, reject) => {
        //try {
        cloudant_client.db.find(
            {
                selector: {
                    "$and": [
                        {
                            _id: {
                                '$regex': "^msg_*"
                            }
                        },
                        {
                            spaceId: cloudant_client.parseDocId(spaceId, 'SPC')
                        },
                        {
                            created: {
                                "$gte": new Date(startDate)
                            }
                        },
                        {
                            created: {
                                "$lte": new Date(endDate)
                            }
                        },
                    ]
                },
                limit: lst,
                skip: skp
            },
            (err, result) => {
                if (err) {
                    console.log("ERROR: ---> " + err);
                    reject(err);
                }
                resolve(result.docs);
            },
        );
    });
}

module.exports = cloudant_client;


text:
{% include html_components/component_includes/componentContentType.html %}

     menu

            {% if include.component-data.image %}

            {% else %}

{{ include.component-data.logo.title}} {{ include.component-data.logo.subtitle}}

            {% endif %}

       {% for menu in posts limit:{{include.component-data.limit}} offset:{{include.component-data.offset}} %}

{{ menu.name }}

        {% endfor %}

       {% for menu in posts limit:{{include.component-data.limit}} offset:{{include.component-data.offset}} %}

{{ menu.name }}

        {% endfor %}


text:
from django.conf import settings
settings.configure()

#from models import BlogPost
from django.db import models
from django.contrib import admin

# Create your models here.
class BlogPost(models.Model):
    title = models.CharField(max_length = 150)
    content = models.TextField()
    timestamp = models.DateTimeField()

class BlogPostAdmin(admin.ModelAdmin):
    list_display = ('title', 'content', 'timestamp')

admin.site.register(BlogPost, BlogPostAdmin)
if __name__ == "__main__":
    f = open("E:\\bak\\sql.txt", "r")
    for line in f:
       content=line.split(",");
       print content[0],content[2]
       p1=BlogPost(title=content[0],content=content[1],timestamp=content[2])
       p1.save()
    f.close()


text:
from binding import *
from src.namespace import llvm

TargetMachine = llvm.Class()

from src.Support.TargetRegistry import Target
from src.ADT.StringRef import StringRef
from src.Support.CodeGen import CodeModel, TLSModel, CodeGenOpt, Reloc
from src.GlobalValue import GlobalValue
from src.DataLayout import DataLayout
if LLVM_VERSION >= (3, 4):
    from src.MC import MCAsmInfo, \
                       TargetInstrInfo, \
                       TargetSubtargetInfo, \
                       TargetRegisterInfo

if LLVM_VERSION < (3, 3):
    from src.TargetTransformInfo import (ScalarTargetTransformInfo,
                                         VectorTargetTransformInfo)
from src.PassManager import PassManagerBase
from src.Support.FormattedStream import formatted_raw_ostream

@TargetMachine
class TargetMachine:
    _include_ = 'llvm/Target/TargetMachine.h'

    CodeGenFileType = Enum('''
                           CGFT_AssemblyFile
                           CGFT_ObjectFile
                           CGFT_Null''')

    delete = Destructor()

    getTarget = Method(const(ref(Target)))

    getTargetTriple = Method(cast(StringRef, str))
    getTargetCPU = Method(cast(StringRef, str))
    getTargetFeatureString = Method(cast(StringRef, str))

    getRelocationModel = Method(Reloc.Model)
    getCodeModel = Method(CodeModel.Model)
    getTLSModel = Method(TLSModel.Model, ptr(GlobalValue))
    getOptLevel = Method(CodeGenOpt.Level)

    hasMCUseDwarfDirectory = Method(cast(Bool, bool))
    setMCUseDwarfDirectory = Method(Void, cast(bool, Bool))

    getDataLayout = Method(const(ownedptr(DataLayout)))

    if LLVM_VERSION < (3, 3):
        getScalarTargetTransformInfo = Method(const(
                                          ownedptr(ScalarTargetTransformInfo)))
        getVectorTargetTransformInfo = Method(const(
                                          ownedptr(VectorTargetTransformInfo)))

    else:
        addAnalysisPasses = Method(Void, ref(PassManagerBase))

    addPassesToEmitFile = Method(cast(bool, Bool),
                                 ref(PassManagerBase),
                                 ref(formatted_raw_ostream),
                                 CodeGenFileType,
                                 cast(bool, Bool)
                                 ).require_only(3)

    if LLVM_VERSION >= (3, 4):
        getSubtargetImpl = Method(const(ownedptr(TargetSubtargetInfo)))

        getMCAsmInfo = Method(const(ownedptr(MCAsmInfo)))

        getInstrInfo = Method(const(ownedptr(TargetInstrInfo)))

        getRegisterInfo = Method(const(ownedptr(TargetRegisterInfo)))


text:
<?php

namespace Sparky7\Api\Response;

use Sparky7\Api\Response;
use Sparky7\Helper\Buffer;
use Sparky7\Helper\Json;

/**
 * API Response class.
 */
class APIResponse extends Response
{
    public $headers;

    public $rid;
    public $code;
    public $errors;
    public $status;
    public $message;
    public $response;

    public $pretty;

    /**
     * Construct.
     */
    final public function __construct()
    {
        $this->code = 200;
        $this->status = true;
        $this->pretty = false;
    }

    /**
     * toArray method.
     *
     * @return array Response
     */
    final public function toArray()
    {
        return [
            'rid' => $this->rid,
            'code' => $this->code,
            'errors' => $this->errors,
            'status' => $this->status,
            'message' => $this->message,
            'response' => $this->response,
        ];
    }

    /**
     * Not found - set response to not found.
     */
    final public function notFound()
    {
        $this->code = 404;
        $this->errors = null;
        $this->status = false;
        $this->message = 'Not found';
        $this->response = null;
    }

    /**
     * Format response into JSON.
     *
     * @param bool $die End on output
     */
    final public function format()
    {
        return ($this->pretty) ? Json::indent(json_encode($this->toArray())) : json_encode($this->toArray());
    }

    /**
     * Get Response headers.
     *
     * @return array Headers
     */
    final public function getHeaders()
    {
        $this->headers = [
            'Access-Control-Allow-Origin: *',
            'Access-Control-Allow-Headers: Authorization, Cache-Control, Content-Type, X-Requested-With',
            'Access-Control-Allow-Methods: HEAD, POST, GET, DELETE, PUT, OPTIONS',
            'Access-Control-Max-Age: 86400',
            'Cache-Control: max-age=0, no-store, no-cache, post-check=0, pre-check=0',
            'Content-Type: application/json; charset=utf-8',
            'Expires: Mon, 26 Jul 1997 05:00:00 GMT',
            'Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT',
            'Pragma: no-cache',
        ];

        if (!is_null($this->rid)) {
            $this->headers[] = 'Request-ID: '.$this->rid;
        }

        return $this->headers;
    }

    /**
     * Send Headers.
     *
     * @param array $overwrite_headers Overwrite headers
     */
    final public function sendHeaders()
    {
        if (headers_sent() || !in_array((int) $this->code, [200, 203, 204, 400, 401, 402, 403, 404, 500, 501, 503])) {
            return;
        }

        Buffer::clear();
        Buffer::gzip();

        http_response_code($this->code);

        foreach ($this->getHeaders() as $header) {
            header($header);
        }
    }
}


text:
/* Licensed under Apache-2.0 */
package com.rabidgremlin.mutters.bot.ink;

public class TaxiInkBot extends InkBot<TaxiInkBotConfiguration>
{

  public TaxiInkBot(TaxiInkBotConfiguration config)
  {
    super(config);
  }

}


text:
require File.dirname(__FILE__) + '/app_root/config/environment'
require 'test_help'
require 'rubygems'
require 'shoulda'

# Run the migrations
ActiveRecord::Migration.verbose = false
ActiveRecord::Migrator.migrate("#{RAILS_ROOT}/db/migrate")

# Setup the fixtures path
ActiveSupport::TestCase.fixture_path = File.join(File.dirname(__FILE__), "fixtures")


text:
<?php
$TRANSLATIONS = array(
"Couldn't delete %s permanently" => "Nuk munda ta eliminoj përfundimisht %s",
"Couldn't restore %s" => "Nuk munda ta rivendos %s",
"Error" => "Veprim i gabuar",
"restored" => "rivendosur",
"Nothing in here. Your trash bin is empty!" => "Këtu nuk ka asgjë. Koshi juaj është bosh!",
"Name" => "Emri",
"Restore" => "Rivendos",
"Deleted" => "Eliminuar",
"Delete" => "Elimino",
"Deleted Files" => "Skedarë të eliminuar"
);
$PLURAL_FORMS = "nplurals=2; plural=(n != 1);";


text:
layout: project_item
pid: 0
name: platform-feelpp
title: "Feel++
Finite Element Library Embedded in C++"
date: 2015-08-17
author:
fullname:
categories: [platform-project]
tags: [cemosis-project]
abstract:
logo: /img/logos/software.png
img:
collaborator: Feel++ Consortium
---

{{ page.title }}

#### Description

Feel++ est notre librairie phare pour la résolution d'équations à
dérivées partielles. Elle est utilisée dans la plupart de nos
collaborations multi-disciplinaires et avec les entreprises.

#### Liens

* Site officiel : [http://www.feelpp.org](http://www.feelpp.org)
* Dépôt de code source git : [https://github.com/feelpp/feelpp](https://github.com/feelpp/feelpp)
* Gitbook : [http://book.feelpp.org](http://book.feelpp.org)
* API Documentation : [http://doc.feelpp.org](http://doc.feelpp.org)

#### Contact

* Christophe Prud'homme : christophe.prudhomme (at) cemosis (dot) fr

#### Brochure


text:
unless Float.const_defined? :INFINITY
  Float::INFINITY = 1.0/0.0
end


text:
//---------------------------------------------------------------------------
#ifndef Export_PBCoreH
#define Export_PBCoreH
//---------------------------------------------------------------------------

//---------------------------------------------------------------------------
#include "MediaInfo/MediaInfo_Internal.h"
//---------------------------------------------------------------------------

namespace MediaInfoLib
{

//***************************************************************************
/// @brief Export_PBCore
//***************************************************************************

class Export_PBCore
{
public :
    //Constructeur/Destructeur
    Export_PBCore ();
    ~Export_PBCore ();

    //Input
    Ztring Transform(MediaInfo_Internal &MI);
};

} //NameSpace
#endif


text:
#pragma once

#include <samchon/TreeMap.hpp>
#include <samchon/library/CriticalAllocator.hpp>

namespace samchon
{
namespace library
{
	/**
	 * @brief A TreeMap ensures concurrency.
	 *
	 * @see library::CriticalAllocator
	 * @see samchon::library
	 * @author Jeongho Nam <http://samchon.org>
	 */
	template <typename Key, typename T, typename _Pr = std::less<Key>>
	using CriticalTreeMap = TreeMap<Key, T, _Pr, CriticalAllocator<std::pair<const Key, T>>>;
};
};


text:
from setuptools import setup
from djangocms_ckandatasetlist import __version__

install_requires=[
    'ckanapi'
]

CLASSIFIERS = [
        'Development Status :: 2 - Pre-Alpha',
        'Environment :: Web Environment',
        'Framework :: Django',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: BSD License',
        'Operating System :: OS Independent',
        'Programming Language :: Python',
        'Topic :: Communications',
        'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
        'Programming Language :: Python :: 2.6',
        'Programming Language :: Python :: 2.7',
]

setup(
    name='djangocms-ckandatasetlist',
    version=__version__,
    description='Displays styled list of recently added CKAN datasets',
    author='Sasha Cuerda',
    author_email='sasha.cuerda@gmail.com',
    url='https://github.com/scuerda/djangocms_ckandatasetlist',
    packages=['djangocms_ckandatasetlist'],
    install_requires=install_requires,
    license='LICENSE.txt',
    platforms=['OS Independent'],
    classifiers=CLASSIFIERS,
    include_package_data=True,
    zip_safe=False
)


text:
package net.nologin.meep.ca;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.*;
import com.actionbarsherlock.app.SherlockActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;
import com.actionbarsherlock.view.MenuItem;
import net.nologin.meep.ca.view.WolframCAView;

/**
 * Main WolframCA activity.  This consists of the custom {@link WolframCAView} taking up the full display, with a
 * few menu options being rendered by the {@link SherlockActivity} superclass.
 *

 * This activity needs the ActionBarSherlock library set as a
 * project dependency!
 *

 * The following menu options are implemented here:
 *

 *
Change Rule: A dialog to choose a different {@link net.nologin.meep.ca.model.WolframRuleTable rule}

 *
Change Zoom: A dialog to choose how many pixels wide to render each CA cell

 *
Back To Top: Scroll the {@link WolframCAView} so tile 0,0 is top center in the surface

 *
Settings: Calls the {@link SettingsActivity}

 *

 */
public class MainActivity extends SherlockActivity {

    // start on a more interesting rule
    private static final int DEFAULT_RULE = 110;

    private WolframCAView caView;

    // local variables for the dialogs before the user commits their choice
    private int ruleDialog_rule;
    private int zoomDialog_zoom;

    @Override
    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.main);

        caView = (WolframCAView) findViewById(R.id.caView);
        caView.setupForRule(DEFAULT_RULE);

        // set "Rule #number" descriptive text in the actionbarsherlock actionbar
        getSherlock().getActionBar().setTitle(
                getResources().getString(R.string.actionbar_ruleSummary,
                        caView.getCurrentRule()));

    }

    @Override
    protected void onResume() {
        super.onResume();

        // not in onCreate as we want this to take effect on return from settings
        caView.setDebugEnabled(WolframUtils.Prefs.getPrefDebugEnabled(this));
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getSupportMenuInflater();
        inflater.inflate(R.menu.actionbar_itemlist, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        switch (item.getItemId()) {

            // "Change Rule" dialog
            case R.id.actionbar_changerule:
                createAndShowRuleDialog();
                return true;

            // "Change Zoom" dialog
            case R.id.actionbar_changezoom:
                createAndShowZoomDialog();
                return true;

            // "Back to Top"
            case R.id.actionbar_backtotop:
                caView.moveToOriginTile();
                return true;

            // "Settings"
            case R.id.actionbar_settings:
                startActivity(new Intent(this, SettingsActivity.class));
                return true;

            default:
                return super.onOptionsItemSelected(item);
        }
    }

    /* Setup and display rule change dialog.  Seek bar with values between 0-255, summary of selected rule and
     * 'prev' and 'next' buttons for finer control of rule selection. */
    private void createAndShowRuleDialog() {

        ruleDialog_rule = caView.getCurrentRule();

        View layout = getLayoutInflater().inflate(R.layout.rule_select, null);

        // set the summary of the selected rule, eg "Rule 110"
        final TextView ruleSummaryTxt = (TextView) layout.findViewById(R.id.ruleDialog_ruleSummaryTxt);
        ruleSummaryTxt.setText(getResources().getString(R.string.ruledialog_ruleSummary, ruleDialog_rule));

        final SeekBar ruleSeek = (SeekBar) layout.findViewById(R.id.ruleDialog_ruleSlider);
        ruleSeek.setMax(255);
        ruleSeek.setProgress(ruleDialog_rule);
        ruleSeek.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {

            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                ruleDialog_rule = progress;
                ruleSummaryTxt.setText(getResources().getString(R.string.ruledialog_ruleSummary, ruleDialog_rule));
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
            }
        });

        layout.findViewById(R.id.ruleDialog_butRulePrev).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ruleDialog_rule = ruleDialog_rule <= 0 ? 255 : ruleDialog_rule - 1;
                ruleSeek.setProgress(ruleDialog_rule); // seekbar listener will update edittext value
            }
        });

        layout.findViewById(R.id.ruleDialog_butRuleNext).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ruleDialog_rule = ruleDialog_rule >= 255 ? 0 : ruleDialog_rule + 1;
                ruleSeek.setProgress(ruleDialog_rule); // seekbar listener will update edittext value
            }
        });

        AlertDialog.Builder builder = new AlertDialog.Builder(this)
                .setTitle(getResources().getString(R.string.ruledialog_title))
                .setCancelable(true)
                .setView(layout)
                .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        getSherlock().getActionBar().setTitle(getResources().getString(R.string.actionbar_ruleSummary, ruleDialog_rule));
                        caView.setupForRule(ruleDialog_rule);
                    }
                })
                .setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        dialog.cancel();
                    }
                });

        builder.create().show();

    }

    /* Setup and display zoom change dialog.  Seek bar with values between 1-16 (in steps of 2), summary of selected
     * zoom level and 'prev' and 'next' buttons for finer control of zoom selection. */
    private void createAndShowZoomDialog() {

        zoomDialog_zoom = caView.getCurrentPxPerCell();

        View layout = getLayoutInflater().inflate(R.layout.zoom_select, null);

        // set the summary of the selected zoom level, eg "4px per cell"
        final TextView zoomSummaryTxt = (TextView) layout.findViewById(R.id.zoomDialog_zoomSummaryTxt);
        zoomSummaryTxt.setText(getResources().getString(R.string.zoomdialog_zoomSummary, zoomDialog_zoom));

        final SeekBar zoomSeek = (SeekBar) layout.findViewById(R.id.zoomDialog_zoomSlider);
        zoomSeek.setMax(16);
        zoomSeek.setProgress(zoomDialog_zoom);
        zoomSeek.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {

            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {

                progress = WolframUtils.sanitizeZoom(progress);
                seekBar.setProgress(progress);

                zoomDialog_zoom = progress;
                zoomSummaryTxt.setText(getResources().getString(R.string.zoomdialog_zoomSummary, zoomDialog_zoom));
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
            }
        });

        layout.findViewById(R.id.zoomDialog_butZoomPrev).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                zoomDialog_zoom = WolframUtils.sanitizeZoom(zoomDialog_zoom - 2);
                zoomSeek.setProgress(zoomDialog_zoom); // seekbar listener will update edittext value
            }
        });

        layout.findViewById(R.id.zoomDialog_butZoomNext).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                zoomDialog_zoom = WolframUtils.sanitizeZoom(zoomDialog_zoom + 2);
                zoomSeek.setProgress(zoomDialog_zoom); // seekbar listener will update edittext value
            }
        });

        AlertDialog.Builder builder = new AlertDialog.Builder(this)
                .setTitle(getResources().getString(R.string.zoomdialog_title))
                .setCancelable(true)
                .setView(layout)
                .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        caView.setupForZoom(zoomDialog_zoom);
                    }
                })
                .setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        dialog.cancel();
                    }
                });

        builder.create().show();

    }

}


text:
/**
 * Placeholder test - checks that an attribute or the content of an
 * element itself is not a placeholder (i.e. "click here" for links).
 */
quail.components.placeholder = function(quail, test, Case, options) {

  var resolve = function (element, resolution) {
    test.add(Case({
      element: element,
      expected: $(element).closest('.quail-test').data('expected'),
      status: resolution
    }));
  };

  test.get('$scope').find(options.selector).each(function() {
    var text = '';
    if($(this).css('display') === 'none' && !$(this).is('title')){
      resolve(this, 'inapplicable');
      return;
    }
    if (typeof options.attribute !== 'undefined') {
      if ((typeof $(this).attr(options.attribute) === 'undefined' ||
            (options.attribute === 'tabindex' &&
              $(this).attr(options.attribute) <= 0
            )
         ) &&
         !options.content
        ) {
        resolve(this, 'failed');
        return;
      }
      else {
        if ($(this).attr(options.attribute) && $(this).attr(options.attribute) !== 'undefined') {
          text += $(this).attr(options.attribute);
        }
      }
    }
    if (typeof options.attribute === 'undefined' ||
      !options.attribute ||
      options.content) {
      text += $(this).text();
      $(this).find('img[alt]').each(function() {
        text += $(this).attr('alt');
      });
    }
    if (typeof text === 'string' && text.length > 0) {
      text = quail.cleanString(text);
      var regex = /^([0-9]*)(k|kb|mb|k bytes|k byte)$/g;
      var regexResults = regex.exec(text.toLowerCase());
      if (regexResults && regexResults[0].length) {
        resolve(this, 'failed');
      }
      else if (options.empty && quail.isUnreadable(text)) {
        resolve(this, 'failed');
      }
      else if (quail.strings.placeholders.indexOf(text) > -1 ) {
        resolve(this, 'failed');
      }
      // It passes.
      else {
        resolve(this, 'passed');
      }
    }
    else {
      if (options.empty && typeof text !== 'number') {
        resolve(this, 'failed');
      }
    }
  });
};


text:
layout: post
title: Animations on Transition with Angular
tags: [thoughts, angular, code-snippets]
description: "tl;dr won't work on init."
image:
  feature: soft-trees.jpg
---

Most Angular animations work by appending and removing CSS classes, which means that ```transitions``` don't work for shit. (Not entirely true; they'll work, but only on second fire. Annoying.) According to this [SO post]() it might be because the browser doesn't have the chance to render it fast enough, as if it isn't aware of its initial state beforehand. Idk, friends.

If you need/want to have a nice fade in on enter, you need to do it with keyframes. Always, essentially.


text:
require_relative '../../test_helper'

class AttributeTransitionCollectionByDefaultTest < StateMachinesTest
  def setup
    @transitions = StateMachines::AttributeTransitionCollection.new
  end

  def test_should_skip_actions
    assert @transitions.skip_actions
  end

  def test_should_not_skip_after
    refute @transitions.skip_after
  end

  def test_should_not_use_transaction
    refute @transitions.use_transactions
  end

  def test_should_be_empty
    assert @transitions.empty?
  end
end


text:
package org.goldonship.designpattern.structural.adapter.interfaceAdapter;

import org.junit.Test;

/**
 * * Created by Goldonship on 2017/10/29.
 **/
public class WrapperTest {

    @Test
    public void testInterfaceWrapper(){
        Sourceable sourceable1 = new SourceStub1();
        Sourceable sourceable2 = new SourceStub2();
        sourceable1.method1();
        sourceable2.method2();
     }

}


text:
import { genUtil } from './util';
import * as _ from 'lodash';
import { Processor } from './Processor';
import {
  TaskGraphNode,
  TaskGraphGraph,
  TaskGraphGraphNode,
  TaskGraphMarkerNode
} from '../deciders/TaskGraph';

export interface TaskGraphNodeDeps extends TaskGraphNode {
  deps: string[];
}

export class TaskGraphBuilder {
  name: string;
  id: string;
  processor: Processor;
  graph: TaskGraphGraph;
  sourceTask: TaskGraphMarkerNode;
  sinkTask: TaskGraphMarkerNode;
  byName: {[nodeName: string]: TaskGraphNode};

  constructor(name: string, args: any, tasks: TaskGraphNode[], processor: Processor) {
    this.name = name;
    this.id = processor.buildId(name);
    this.processor = processor;
    this.graph = {
      nodes: {},
      edges: {},
      revEdges: {},
      sourceNode: '',
      sinkNode: ''
    };

    this.sourceTask = this.createCheckTask(args, tasks, 'sourceTask', 'Starting');
    this.sinkTask = this.createCheckTask(args, tasks, 'sinkTask', 'Finished');
    this.byName = _.keyBy<TaskGraphNode>(tasks, 'name');
    this.graph = tasks.reduce(this.reduceToGraph.bind(this), this.graph);
    this.addSinkNodeEdges();
    this.addSourceSinkNodes();
  }

  createCheckTask(args, tasks, name, label): TaskGraphMarkerNode {
    return {
      name: name,
      id: this.processor.buildId(name),
      currentPath: this.processor.getCurrentPath().concat(name),
      type: 'decision',
      handler: 'recordMarker',
      parameters: {
        status: `${label} tasks in ${this.processor.getCurrentPathStr()}, ${tasks.length} total tasks, args: ${genUtil.serializeArgs(args)}`
      }
    };
  }

  getGraph(): TaskGraphGraphNode {
    // get rid of rev edges
    // delete this.graph.revEdges;
    return {
      type: 'decision',
      handler: 'taskGraph',
      workflow: {name: this.processor.getWorkflowName()},
      parentWorkflow: this.processor.getParentWorkflowDetails(),
      currentPath: this.processor.getCurrentPath(),
      id: this.id,
      name: this.name,
      maxRetry: this.processor.getMaxRetry(),
      parameters: {
        graph: this.graph
      }
    };
  }

  addSinkNodeEdges() {
    // find nodes with no deps and attach to sink node
    let sinkEdges: string[] = [];
    if (!this.graph.revEdges) {
      throw new Error('unexpected, revEdges not computed');
    }
    for (let taskId in this.graph.revEdges) {
      if (this.graph.revEdges[taskId].length === 0) {
        this.graph.revEdges[taskId] = [this.sinkTask.id];
        sinkEdges.push(taskId);
      }
    }
    this.graph.edges[this.sinkTask.id] = sinkEdges;
  }

  addSourceSinkNodes() {
    this.graph.nodes[this.sourceTask.id] = this.sourceTask;
    this.graph.nodes[this.sinkTask.id] = this.sinkTask;
    this.graph.sourceNode = this.sourceTask.id;
    this.graph.sinkNode = this.sinkTask.id;
  }

  reduceToGraph(graph: TaskGraphGraph, task: TaskGraphNodeDeps) {
    if (Object.keys(task).length === 0) {
      throw new Error('empty task passed. not cool');
    }
    // build up the graph with edges both direction for convience for now...
    // TODO: figure out which way it makes more sense to have edges...

    // convert named deps to ids to get uniqueness
    task.deps = task.deps || [];
    var idDeps = task.deps.map((dep) => {
      if (!this.byName[dep]) {
        throw new Error(`cannot find task with name ${dep} in ${task.name}`);
      }
      return this.byName[dep].id;
    });

    // connect all nodes with no deps to source node
    if (idDeps.length === 0) {
      idDeps.push(this.sourceTask.id);
    }

    // compute reverse edges
    if (!graph.revEdges) {
      throw new Error('unexpected case, graph.revEdges null');
    }
    graph.revEdges[task.id] = graph.revEdges[task.id] || [];
    idDeps.forEach((idDep) => {
      graph.revEdges![idDep] = graph.revEdges![idDep] || [];
      graph.revEdges![idDep].push(task.id);
    });
    delete task.deps;

    // atttach to graph
    graph.edges[task.id] = idDeps;
    graph.nodes[task.id] = task;
    return graph;
  }
}


text:
<!DOCTYPE html>
<link href="resources/grid.css" rel="stylesheet">

This test checks that positioned grid items can be placed directly on the padding.


text:
Pattern: Slow DB query

Issue: -

## Description

Flag potentially slow queries.

## Further Reading

* [VIP Go](https://vip.wordpress.com/documentation/vip-go/code-review-blockers-warnings-notices/#uncached-pageload)
* [WordPress.DB.SlowDBQuery](https://github.com/WordPress/WordPress-Coding-Standards/tree/develop/WordPress/Sniffs/DB/SlowDBQuerySniff.php)


text:
FROM fedora:23
MAINTAINER christophe.furmaniak@gmail.com

RUN dnf clean all && \
    dnf update -y && \
    dnf install -y python-pip gcc make redhat-rpm-config python-devel && \
    pip install ansible 'dopy>=0.3.5,<=0.3.5' && \
    mkdir -p /etc/ansible && \
    echo '[local]' > /etc/ansible/hosts && \
    echo localhost >> /etc/ansible/hosts && \
    echo >> /etc/ansible/hosts


text:
import random

from pyramid import httpexceptions

from kinto.core.errors import ERRORS

from . import BaseTest

class SortingTest(BaseTest):
    def setUp(self):
        super(SortingTest, self).setUp()
        self.patch_known_field.start()

        indices = list(range(20))
        random.shuffle(indices)

        for i in indices:
            record = {
                'title': 'MoFo #{0:02}'.format(i),
                'status': i % 4,
                'unread': (i % 2 == 0)
            }
            self.model.create_record(record)

    def test_sort_works_with_empty_list(self):
        self.resource.model.parent_id = 'alice'
        self.resource.request.GET = {'_sort': 'unread'}
        result = self.resource.collection_get()
        self.assertEqual(len(result['data']), 0)

    def test_sort_on_unknown_attribute_raises_error(self):
        self.patch_known_field.stop()
        self.resource.request.GET = {'_sort': 'foo'}
        self.assertRaises(httpexceptions.HTTPBadRequest,
                          self.resource.collection_get)

    def test_filter_errors_are_json_formatted(self):
        self.patch_known_field.stop()
        self.resource.request.GET = {'_sort': 'foo'}
        try:
            self.resource.collection_get()
        except httpexceptions.HTTPBadRequest as e:
            error = e
        self.assertEqual(error.json, {
            'errno': ERRORS.INVALID_PARAMETERS.value,
            'message': "querystring: Unknown sort field 'foo'",
            'code': 400,
            'error': 'Invalid parameters',
            'details': [{'description': "Unknown sort field 'foo'",
                         'location': 'querystring',
                         'name': None}]})

    def test_sort_on_last_modified_is_supported(self):
        self.patch_known_field.stop()
        self.resource.request.GET = {'_sort': '-last_modified'}
        result = self.resource.collection_get()
        tstamp = self.model.timestamp()
        self.assertEqual(result['data'][0]['last_modified'], tstamp)

    def test_single_basic_sort_by_attribute(self):
        self.resource.request.GET = {'_sort': 'title'}
        result = self.resource.collection_get()
        self.assertEqual(len(result['data']), 20)
        self.assertEqual(result['data'][0]['title'], 'MoFo #00')
        self.assertEqual(result['data'][-1]['title'], 'MoFo #19')

    def test_single_basic_sort_by_attribute_reversed(self):
        self.resource.request.GET = {'_sort': '-title'}
        result = self.resource.collection_get()
        self.assertEqual(len(result['data']), 20)
        self.assertEqual(result['data'][0]['title'], 'MoFo #19')
        self.assertEqual(result['data'][-1]['title'], 'MoFo #00')

    def test_multiple_sort(self):
        self.resource.request.GET = {'_sort': 'status,title'}
        result = self.resource.collection_get()
        self.assertEqual(result['data'][0]['status'], 0)
        self.assertEqual(result['data'][0]['title'], 'MoFo #00')
        self.assertEqual(result['data'][1]['status'], 0)
        self.assertEqual(result['data'][1]['title'], 'MoFo #04')
        self.assertEqual(result['data'][-2]['status'], 3)
        self.assertEqual(result['data'][-2]['title'], 'MoFo #15')
        self.assertEqual(result['data'][-1]['status'], 3)
        self.assertEqual(result['data'][-1]['title'], 'MoFo #19')

    def test_multiple_sort_with_order(self):
        self.resource.request.GET = {'_sort': 'status,-title'}
        result = self.resource.collection_get()
        self.assertEqual(result['data'][0]['status'], 0)
        self.assertEqual(result['data'][0]['title'], 'MoFo #16')
        self.assertEqual(result['data'][1]['status'], 0)
        self.assertEqual(result['data'][1]['title'], 'MoFo #12')
        self.assertEqual(result['data'][-2]['status'], 3)
        self.assertEqual(result['data'][-2]['title'], 'MoFo #07')
        self.assertEqual(result['data'][-1]['status'], 3)
        self.assertEqual(result['data'][-1]['title'], 'MoFo #03')

    def test_boolean_sort_brings_true_last(self):
        self.resource.request.GET = {'_sort': 'unread'}
        result = self.resource.collection_get()
        self.assertEqual(result['data'][0]['unread'], False)
        self.assertEqual(result['data'][-1]['unread'], True)

    def test_default_sort_is_last_modified_desc_by_default(self):
        self.resource.request.GET = {'_sort': ''}
        result = self.resource.collection_get()
        tstamp = self.model.timestamp()
        self.assertEqual(result['data'][0]['last_modified'], tstamp)

    def test_default_sort_is_last_modified_records_have_same_status(self):
        self.resource.request.GET = {'_sort': 'status'}
        result = self.resource.collection_get()
        self.assertEqual(result['data'][0]['status'], 0)
        self.assertEqual(result['data'][1]['status'], 0)
        self.assertGreater(result['data'][0]['last_modified'],
                           result['data'][1]['last_modified'])

class SubobjectSortingTest(BaseTest):
    def setUp(self):
        super(SubobjectSortingTest, self).setUp()
        self.patch_known_field.start()

        indices = list(range(20))
        random.shuffle(indices)

        for i in indices:
            record = {
                'party': {'candidate': 'Marie', 'voters': i},
                'location': 'Creuse'
            }
            self.model.create_record(record)

    def test_records_can_be_sorted_by_subobjects(self):
        self.resource.request.GET = {'_sort': 'party.voters'}
        result = self.resource.collection_get()
        values = [item['party']['voters'] for item in result['data']]
        self.assertEqual(sorted(values), values)

    def test_subobjects_sorting_is_ignored_if_not_object(self):
        self.resource.request.GET = {'_sort': 'location.city'}
        result = self.resource.collection_get()
        values = [item['party']['voters'] for item in result['data']]
        self.assertNotEqual(sorted(values), values)


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Jb. nassau. Ver. Naturk. 23-24: 161 (1870)

#### Original name
Trematosphaeria Fuckel

### Remarks
null


text:
@implementation GCIPViewController_Pad {
    GCIPAssetPickerController *_assetPickerController;
    GCIPGroupPickerController *_groupPickerController;
}

#pragma mark - object methods

- (id)init {
    self = [super init];
    if (self) {

        // create group picker controller
        _groupPickerController = [[GCIPGroupPickerController alloc] init];
        _groupPickerController.clearsSelectionOnViewWillAppear = NO;
        _groupPickerController.showDisclosureIndicators = NO;
        _groupPickerController.delegate = self;
        self.title = _groupPickerController.title;
        [self addChildViewController:_groupPickerController];
        [_groupPickerController didMoveToParentViewController:self];

        // create asset picker
        _assetPickerController = [[GCIPAssetPickerController alloc] init];
        [self addChildViewController:_assetPickerController];
        [_assetPickerController didMoveToParentViewController:self];

    }
    return self;
}

- (id)forwardingTargetForSelector:(SEL)selector {
    UIViewController *parent = self.parentViewController;
    if ([parent respondsToSelector:selector]) {
        return parent;
    }
    else { return nil; }
}

- (void)reloadAssets {
    [self.childViewControllers makeObjectsPerformSelector:@selector(reloadAssets)];
}

- (UINavigationItem *)navigationItem {
    return _assetPickerController.navigationItem;
}

#pragma mark - view lifecycle

- (void)viewDidLoad {
    [super viewDidLoad];

    // self
    self.view.backgroundColor = [UIColor blackColor];

    // placeholder
    UIView *view;

    // group picker
    view = _groupPickerController.view;
    view.frame = CGRectMake(0.0, 0.0, 320.0, self.view.bounds.size.height);
    view.autoresizingMask = UIViewAutoresizingFlexibleHeight;
    [self.view addSubview:view];

    // asset picker
    view = _assetPickerController.view;
    view.frame = CGRectMake(321.0, 0.0, self.view.bounds.size.width - 321.0, self.view.bounds.size.height);
    view.autoresizingMask = (UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth);
    [self.view addSubview:view];

}

#pragma mark - group picker delegate

- (void)groupPicker:(GCIPGroupPickerController *)picker didSelectGroup:(ALAssetsGroup *)group {
    _assetPickerController.groupURL = [group valueForProperty:ALAssetsGroupPropertyURL];
}

@end


text:
"""This script downloads traffic data from tkm.ibb.gov.tr"""

import argparse
import signal
import logging as log
import os
from os import path
from os.path import join as joinp
import re
import threading
import time
import urllib2 as ul
from collections import namedtuple as nt

from datetime import datetime as dt
import datetime
from dateutil import tz

import tkmdecrypt as td
import compression as c

# region initial definitions

log.basicConfig(format='%(asctime)s %(levelname)s %(name)s %(message)s',
                filename='tkm.log', level=log.INFO)
logger = log.getLogger(__name__)
logger.root.name = 'tkm.py'

SENSOR_DATA = nt('SensorData', 'id speed color')
TKM_DATA = nt('TkmData', 'date e_tag filename data')

_stop_events = []
_terminate = False
_run_time = -1
# _file_pid = ""

def __init__():
    if '__file__' in globals():
        cdir = os.path.dirname(os.path.realpath(__file__))
    else:
        cdir = os.getcwd()
    _dir = nt('DirObject', 'cur data static')(
        *[joinp(cdir, d) for d in ['', 'database/', 'static_files/']])
    # pylint: disable=W0106
    [os.makedirs(p) for p in _dir if not path.exists(p)]
    main_url = 'http://tkm.ibb.gov.tr/'
    # File Names for static files
    fl_road = ['r{0:d}.txt'.format(x) for x in range(5)]
    fl_other = ['d{0:02d}.txt'.format(x) for x in range(1, 10)]
    static_files_url = 'YHarita/res/'
    # Create list of URLs to use in module.
    _url = nt('UrlList',
              'trafficindex trafficdata parkingdata '
              'announcements weatherdata road other')(
        *(tuple([joinp(main_url, url) for url in [
            'data/IntensityMap/' +
            url + '.aspx' for url in [
                'TrafficIndex',
                'TrafficDataNew',
                'ParkingLotData',
                'AnnouncementData',
                'WeatherData']]]) +
            ([joinp(main_url, static_files_url, fn) for fn in fl_road],
             [joinp(main_url, static_files_url, fn) for fn in fl_other])))
    return _url, _dir

URL, DIR = __init__()

# endregion

# region private functions

def _now():
    """
    Return current DateTime in Local Time Zone.

    :rtype: dt
    """
    return dt.now().replace(tzinfo=tz.tzlocal())

def _add_e_tag(f, e_tag):
    return '{0}.{2}{1}'.format(*(path.splitext(f) + (e_tag,)))

def _write_to_file(f, data, last_modified, e_tag=None):
    """
    Write data to a file with last_modified time.

    :param f: Full path to file
    :param data: Unicode data to write to file
    :param last_modified: Last modified date object
    :rtype: None
    """
    if e_tag:  # if e_tag exists, add to filename
        f = _add_e_tag(f, e_tag)
    write_type = 'wb' if e_tag else 'a'
    with open(f, write_type) as fl: fl.write(data)
    # change creation and last modified datetime of file.
    os.utime(f, (time.mktime(_now().timetuple()),
                 time.mktime(last_modified.timetuple())))

def _static_file_write(tkmd):
    """Write tkmd data to a static file.

    :param tkmd: TKM_DATA type object
    :type tkmd: TKM_DATA
    :rtype: None
    """
    _write_to_file(joinp(DIR.static, tkmd.filename),
                   tkmd.data, tkmd.date)

def _static_file_read(fl):
    fl = joinp(DIR.static, fl)
    data = None
    if path.exists(fl):
        with open(fl, "rb") as f:
            data = f.read().decode('UTF-8')
    return data

def _static_file_get_modified_time(f):
    f = joinp(DIR.static, f)
    if path.exists(f):
        return dt.fromtimestamp(
            path.getmtime(f)
        ).replace(tzinfo=tz.tzlocal())
    return None

def _urlopen(url, k=0):
    """Send a request to url.

    :param url: Url to open
    :param k: Only for internal use
    :return: (url_handle, local_last_modified, e_tag)
    :rtype: tuple
    """
    from socket import error as SocketError
    import errno

    file_with_e_tag = path.basename(url)
    try:
        url_handle = ul.urlopen(ul.Request(url))
    # pylint: disable=W0703
    except Exception as e:
        if k < 5:
            k += 1
            return _urlopen(url, k)
        else:
            url_handle = None
            log.error('%s -> %s STOPPED. saved as NA', file_with_e_tag, str(e))
    if url_handle:
        h = url_handle.info()
        # this value changes if file at url is modified
        e_tag = h.getheader("ETag")
    else:
        h = e_tag = None
    if e_tag:
        e_tag = e_tag.replace('"', '')  # WTF?
        e_tag = e_tag.replace(':', '').upper()  # make e_tag filename friendly
        local_last_modified = dt.fromtimestamp(
            time.mktime(
                time.strptime(
                    h.getheader("Last-Modified"),
                    '%a, %d %b %Y %H:%M:%S %Z'))
        ).replace(tzinfo=tz.tzutc()).astimezone(tz.tzlocal())
        file_with_e_tag = _add_e_tag(file_with_e_tag, e_tag)
    else:  # if e_tag value is None, do not trust to last modified date.
        local_last_modified = _now()
        file_with_e_tag = _add_e_tag(file_with_e_tag,
                                     _now().strftime('%Y%m%d'))
        file_with_e_tag = path.splitext(file_with_e_tag)[0] + '.csv'
    return url_handle, local_last_modified, e_tag, file_with_e_tag

def _get_filename_with_e_tag(url, e_tag=None):
    last_modified = None
    f = path.basename(url)
    if e_tag:
        f = _add_e_tag(f, e_tag)
    else:
        (_, last_modified, _, f) = _urlopen(url)
    return f, last_modified

def _static_file_compare_last_modified(url):
    """Compare local and remote files last modified date.

    :param url:  Url to open or StaticFile object
    :return: if file was modified, return a
            tuple (url_handle, local_last_modified, e_tag) else None.
    :type url: str or tuple
    :rtype: tuple
    """
    ret = _urlopen(url)
    f, _ = _get_filename_with_e_tag(url, ret[2])
    last_modified = ret[1]
    if last_modified == _static_file_get_modified_time(f): return None
    return ret

def _get_data(url, key=None, decrypt=True):
    """Download/Get and decrypts data from tkm web site.

    :param url: Full url to data or a tuple from _urlopen()
    :param key: Encryption key
    :return: TKM_DATA object
    :type url: str or tuple
    :type key: str
    :rtype: TKM_DATA
    """
    def _get_data_internal(_url, _key, k=0):
        url_handle, _last_modified, _e_tag, _f_e_tag = _url \
            if isinstance(_url, tuple) else _urlopen(_url)

        if not _e_tag:
            _last_modified = _run_time

        if url_handle:
            _data = url_handle.read()
            if decrypt:
                _data = td.decrypt0(_data, _key) \
                    if _key else td.decrypt2(_data)

            if _data == 'error' or _data == 'no_data':
                if k < 5:
                    k += 1
                    (_data, _e_tag, _f_e_tag, _last_modified,
                     k) = _get_data_internal(_url, _key, k)
                else:
                    e = "%s returned '%s'. saved as NA"
                    log.error(e, path.basename(_url), _data)
                    _data = 'NA'
        else:
            _data = 'NA'

        return _data, _e_tag, _f_e_tag, _last_modified, k

    (data, e_tag, f_e_tag, last_modified, _) = _get_data_internal(url, key)
    data = data.replace(';', '|').replace('|&', '&')
    if len(data) > 0:
        if data[len(data) - 1] == '&': data = data[:len(data) - 1]
    return TKM_DATA(date=last_modified, e_tag=e_tag,
                    filename=f_e_tag, data=data)

def _get_static_file_data_if_modified(url):
    """Get static file data if modified.

    First checks for last modified date for the local and remote files and
    latter if last modified dates are different, downloads the remote file
    and compares to local one.

    :param url: url of remote file
    :return: remote file data if modified else None
    :rtype: TKM_DATA
    """
    ret = _static_file_compare_last_modified(url)
    if ret:  # if modified
        tkmd = _get_data(ret)
        if tkmd.data != _static_file_read(ret[3]): return tkmd
    return None

def _static_file_download(url):
    """Download a static file.

    :param url: url to file
    :type url: str
    :rtype: None
    """
    tkmd = _get_static_file_data_if_modified(url)
    if tkmd:
        _static_file_write(tkmd)
        info = tkmd.filename + ' > DOWNLOADED.'
        log.info(info)
        print info
    return tkmd

# endregion

# region public functions

def get(t):
    """ Get data by type

    :t: type of data ['traffic_data', 'traffic_index',
                      'parking_data', 'announcements', 'weather_data']
    :return: TKM_DATA object
    """
    if t not in ['traffic_data', 'traffic_index',
                 'parking_data', 'announcements', 'weather_data']:
        raise ValueError('get_data(t) -> t is not proper option')
    try:
        if t == "traffic_data":
            return _get_data(URL.trafficdata, "62403715")
        elif t == "traffic_index":
            return _get_data(URL.trafficindex, "60413275")
        elif t == "parking_data":
            return _get_data(URL.parkingdata, "74205136")
        elif t == "announcements":
            return _get_data(URL.announcements, "50614732")
        elif t == "weather_data":
            return _get_data(URL.weatherdata, "26107354")
    except Exception as e:  # pylint: disable=W0703
        err = t + '-> ' + str(e)
        log.error(err)
    finally:
        pass
    return None

def get_traffic_index():
    """Download Traffic Index.

    :rtype: TKM_DATA
    :return: TKM_DATA object
    """
    return get("traffic_index")

def get_traffic_data():
    """Download Traffic Data.

    :rtype: TKM_DATA
    :return: TKM_DATA object
    """
    return get("traffic_data")

def get_parking_data():
    """Download Parking Data.

    :rtype: TKM_DATA
    :return: TKM_DATA object
    """
    return get("parking_data")

def get_announcements():
    """Download Announcements.

    :rtype: TKM_DATA
    :return: TKM_DATA object
    """
    return get("announcements")

def get_weather_data():
    """Download Weather Data.

    :rtype: TKM_DATA
    :return: TKM_DATA object
    """
    return get("weather_data")

def download_static_files(url_list=URL.road + URL.other):
    """Download Static Files.

    :type url_list: list
    :param url_list: List of URL
    :rtype: None
    """
    if isinstance(url_list, str): url_list = [url_list]
    for u in url_list: _static_file_download(u)
    if '_logged' not in globals():  # log once per session
        log.info('All Static Files are up-to-date.')
        globals()['_logged'] = 1

def download_roads():
    """Download and save road files (If files were not modified).

    :rtype: None
    """
    download_static_files(URL.road)

def file_is_modified(url):
    """Check if a remote file was modified or not.

    :type url: str
    :param url: url to file
    :return: True if file is modified else False
    :rtype: bool
    """
    try:
        ret = _static_file_compare_last_modified(url)
        return ret is not None
    # pylint: disable=W0703
    except Exception as e:
        err = '{0} -> {1}'.format(path.basename(url), str(e))
        log.error(err)
        print err
    finally:
        pass

def roads_are_modified():
    """Check if roads are modified or not.

    :rtype: list
    :return: list of bool
    """
    return [file_is_modified(u) for u in URL.road]

def parse_speed_data(tkmd):
    """Parse speed data and store the result in a hierarchical list object.

    :param tkmd: TKM_DATA object
    :return: TKM_DATA
    """
    data = list()
    # Split tkm.data by & (remove empty elements)
    for l in [x for x in tkmd.data.split('&') if not re.match(r'^\s*$', x)]:
        # split segment value by '|' (remove empty elements)
        token = [x for x in l.split('|') if not re.match(r'^\s*$', x)]
        if token == '' or len(token) < 3: continue
        s = SENSOR_DATA(id=int(token[0]), speed=int(token[1]),
                        color=int(token[2]))
        data.append(s)
    return TKM_DATA(date=tkmd.date, data=data)

def save_instant_data(tkmd):
    """Save TKM_DATA object to file.

    :type tkmd: TKM_DATA
    :param tkmd:
    :rtype: None
    """
    f = joinp(DIR.data, tkmd.filename)
    data = tkmd.date.strftime("%Y-%m-%d %H:%M:%S") + ';' + tkmd.data + '\r\n'
    _write_to_file(f, data, tkmd.date)

def compress_files():
    """Compresses downloaded data files."""
    lcsv = [f for f in os.listdir(DIR.data) if f.endswith('.csv')]
    today_e_tag = _now().strftime('%Y%m%d')
    for f in lcsv:
        ff = os.path.join(DIR.data, f)
        if today_e_tag not in ff:
            c.compress(ff)
            log.info('%s compressed.', os.path.basename(ff))
            os.remove(ff)

def run_action(a):
    """ Run specified action. """
    actions = ['traffic_data', 'traffic_index', 'parking_data',
               'announcements', 'weather_data', 'static_files',
               'compress']
    if a in actions:
        try:
            if a == "static_files":
                download_static_files()
            elif a == "compress":
                compress_files()
            else:
                save_instant_data(get(a))
        except Exception as e:  # pylint: disable=W0703
            err = a + ' -> ' + str(e)
            log.error(err)
        finally:
            pass
    else:
        raise ValueError('selected action must be one of %s' % str(actions))

def worker(action, rep_sec, run_on, stop_event):
    """ Thread worker """
    fmt = '%Y-%m-%d %H:%M:%S'

    def _calc_run_on(run_on, delta=0):
        if isinstance(run_on, str):
            l = len(run_on)
            t = _now().strftime(fmt)
            run_on = t[:-l] + run_on
            run_on = dt.strptime(run_on, fmt).replace(tzinfo=tz.tzlocal())
        while run_on < _now():
            run_on = run_on + datetime.timedelta(0, delta)
            log.debug("run_on=%s" % run_on)
        return run_on.strftime(fmt)

    global _run_time  # pylint: disable=W0603
    a, b = (_now(), 1) if run_on == 'immediate' else (run_on, 60)
    run_on = _calc_run_on(a, b)
    if rep_sec > 0: log.info("Thread " + action + " started")
    while not stop_event.is_set():
        if _now().strftime(fmt) == run_on:
            _run_time = dt.strptime(run_on, fmt)
            run_action(action)
            if rep_sec <= 0: break
            time.sleep(rep_sec * 0.9)
        run_on = _calc_run_on(run_on, rep_sec)
        time.sleep(0.2)
    if rep_sec > 0: log.info("Thread " + action + " stopped")

def main():
    """Entry point."""
    def signal_handler(*args):  # pylint: disable=W0613
        """ Handle signals from system."""
        # Stop threads
        for se in _stop_events: se.set()
        log.info("Terminating threads...")
        global _terminate  # pylint: disable=W0603
        _terminate = True
    signal.signal(signal.SIGTERM, signal_handler)
    signal.signal(signal.SIGTSTP, signal_handler)
    signal.signal(signal.SIGINT, signal_handler)

    p = argparse.ArgumentParser(
        description='Save data from http://tkm.ibb.gov.tr',
        epilog='Example of use')
    args = [['-t', '--traffic-data', 'save traffic data'],
            ['-i', '--traffic-index', 'save traffic index'],
            ['-p', '--parking-data', 'save parking data'],
            ['-a', '--announcements', 'save announcements'],
            ['-w', '--weather-data', 'save weather data'],
            ['-s', '--static-files', 'save static files'],
            ['-c', '--compress', 'compress old csv files']]
    for a in args: p.add_argument(a[0], a[1], action="store_const",
                                  default=None, const='func', help=a[2])

    p.add_argument('-o', '--on', default='immediate',
                   type=str, help='start on time {default: immediate}')
    p.add_argument('-r', '--repeat', default=0, type=int, dest='rep',
                   help='repeat every n seconds after start ' +
                   '{default: Do not repeat}')

    args = p.parse_args()

    threads = []
    for a, v in sorted(vars(args).items()):
        if v == 'func':
            te = threading.Event()
            threads.append(threading.Thread(target=worker,
                                            args=[a, args.rep, args.on, te]))
            _stop_events.append(te)

    if args.rep > 0:
        log.info('----------------------------------------------------------')
        log.info('Module started in continuous mode')

    # try to start each thread in same time as far as possible
    for t in threads:
        # t.daemon = True
        t.start()

    # do not let main thread end soon
    # this line helps to keep it alive and
    # catch signals to exit properly.
    while not _terminate or all([t.isAlive() for t in threads]):
        time.sleep(10)

    if args.rep > 0: log.info('Module terminated gracefully')

# endregion

if __name__ == "__main__":
    main()


text:
var Router = require('../frontend/js/lib/router')();

Router
.add('api/version', require('./api/version'))
.add('api/user/login', require('./api/user-login'))
.add('api/user/logout', require('./api/user-logout'))
.add('api/user', require('./api/user'))
.add('api/friends/find', require('./api/friends-find'))
.add('api/friends/add', require('./api/friends-add'))
.add('api/friends', require('./api/friends'))
.add('api/content/share', require('./api/content-share'))
.add('api/content/like', require('./api/content-like'))
.add('api/content', require('./api/content'))
.add('api/pages/:id', require('./api/pages'))
.add('api/pages', require('./api/pages'))
.add(require('./api/default'));

module.exports = function(req, res) {
  Router.check(req.url, [req, res]);
}