text:
layout:     post
title:      "The saga of Sagas"
subtitle:   "Category: React"
date:       2017-02-28 09:00:00
author:     "Tom Hanson"
tags:       "JavaScript,  React"
categories: "React"
header-img: "img/sagas.jpg"
---

Let me start you off with a bit of history about this one...

I started making a small portfolio site for myself using React. It is going to be buzzword central when its finished with things such as React, Redux, Redux Sagas etc... but I figured what the hell, you only live once!
My first pass at this was to just simply call Axios in componentDidMount. I can't see any reason why this is inherently wrong if you were just adding a tiny component inside a pre build website but as previously mentioned I am using Redux
so even though this actually did work, something rang an alarm bell for me that this was wrong.

After thinking about this for a while I remembered something Wes Bos said in one of his Redux videos about using something called middleware and his recommendations were Redux Thunk & Redux Sagas. This was a good starting point so I did some googling and Redux Saga seemed to come out on top based on the fact that it was using JavaScript generators(fancy new style JS), so I went for it!

You can find the docs here and although they are incredibly in depth I did struggle with quite a bit of unfamiliar syntax to me

At this point I was getting nowhere fast until I stumbled across this tutorial by a guy called Dave Kiss. It really helped me grasp some of the basics and after a brief twitter exchange for him to show me a few more niche things I ended up with a working saga! Success.

I ended up with code looking like this:

   const getPosts = state => state.posts;
    export function *shouldFetchPostAsync(action) {
    try {
        //get my current posts from store
        const posts = yield select(getPosts);
        let response;
        //check if the post slug I am requested is in the store already
        if(posts.length) {
            response = posts.filter( (item) => {
               if(item.slug === action.postID) {
                   return item;
               }
               return false;
            });
            yield put({type: 'TOGGLE_LOADER', response})
        } else {
            response = yield call(axios.get, `${BASEURL}/wp/v2/projects?slug=${ action.postID }`);
            function arrayUnique(array) {
                let a = array.concat();
                for(let i=0; i<a.length; ++i) {
                    for(let j=i+1; j<a.length; ++j) {
                        if(a[i] === a[j])
                            a.splice(j--, 1);
                    }
                }
                return a;
            }
            // concatenate both arrays and then filter them for only unique ones
            response.data = arrayUnique(posts.concat(response.data));

            yield put({type: 'FETCH_POSTS_SUCCEEDED', response})
        }

    } catch(e) {
        console.log('error', e);
    }
}

export function *watchshouldFetchPost() {
    yield takeEvery('SHOULD_FETCH_POST', shouldFetchPostAsync)
}

export default function *rootSaga() {
    yield [
        watchshouldFetchPost()
    ]
}

The tutorial I mentioned will do a way better job than I can explaining the guts of this but there are a couple of things I would like to mention

Firstly, the following line:

    const getPosts = state => state.posts;

will actually check my store and grab my posts. That is so I can run a small check to see if I have any posts yet. If I do then I will just find that post and return it, If I dont then I will run the http request.
This is basically just a buffer to prevent requests every time the components load.

My thinking behind this is that from a list of posts you cannot get to the individual post without clicking its link(and the posts data will therefore already have been requested) and if you do land straight on the page there will be no posts so I will go and fetch that one and put it in my store

the second part is this:

    function arrayUnique(array) {
        let a = array.concat();
        for(let i=0; i<a.length; ++i) {
            for(let j=i+1; j<a.length; ++j) {
                if(a[i] === a[j])
                    a.splice(j--, 1);
            }
        }
        return a;
    }

This basically takes an array and checks no posts are the same in it. Just so I never have any duplicate posts in my store - though as I look at it now I am wondering if I will ever need that so that may go!

Anyway, thats about it for sagas for now. I will hopefully do an updated post when I actually know a bit more but for now it is working and I soret of understand why!

back to learning!


text:
/* Author: Wim Meeussen */

#include "urdf_parser/urdf_parser.h"
#include <iostream>
#include <fstream>

using namespace urdf;
using namespace std;

void addChildLinkNames(LinkConstSharedPtr link, ofstream& os)
{
  os << "\"" << link->name << "\" [label=\"" << link->name << "\"];" << endl;
  for (std::vector<LinkSharedPtr>::const_iterator child = link->child_links.begin(); child != link->child_links.end(); child++)
    addChildLinkNames(*child, os);
}

void addChildJointNames(LinkConstSharedPtr link, ofstream& os)
{
  double r, p, y;
  for (std::vector<LinkSharedPtr>::const_iterator child = link->child_links.begin(); child != link->child_links.end(); child++){
    (*child)->parent_joint->parent_to_joint_origin_transform.rotation.getRPY(r,p,y);
    os << "\"" << link->name << "\" -> \"" << (*child)->parent_joint->name
       << "\" [label=\"xyz: "
       << (*child)->parent_joint->parent_to_joint_origin_transform.position.x << " "
       << (*child)->parent_joint->parent_to_joint_origin_transform.position.y << " "
       << (*child)->parent_joint->parent_to_joint_origin_transform.position.z << " "
       << "\\nrpy: " << r << " " << p << " " << y << "\"]" << endl;
    os << "\"" << (*child)->parent_joint->name << "\" -> \"" << (*child)->name << "\"" << endl;
    addChildJointNames(*child, os);
  }
}

void printTree(LinkConstSharedPtr link, string file)
{
  std::ofstream os;
  os.open(file.c_str());
  os << "digraph G {" << endl;

  os << "node [shape=box];" << endl;
  addChildLinkNames(link, os);

  os << "node [shape=ellipse, color=blue, fontcolor=blue];" << endl;
  addChildJointNames(link, os);

  os << "}" << endl;
  os.close();
}

int main(int argc, char** argv)
{
  if (argc != 2){
    std::cerr << "Usage: urdf_to_graphiz input.xml" << std::endl;
    return -1;
  }

  // get the entire file
  std::string xml_string;
  std::fstream xml_file(argv[1], std::fstream::in);
  while ( xml_file.good() )
  {
    std::string line;
    std::getline( xml_file, line);
    xml_string += (line + "\n");
  }
  xml_file.close();

  ModelInterfaceSharedPtr robot = parseURDF(xml_string);
  if (!robot){
    std::cerr << "ERROR: Model Parsing the xml failed" << std::endl;
    return -1;
  }
  string output = robot->getName();

  // print entire tree to file
  printTree(robot->getRoot(), output+".gv");
  cout << "Created file " << output << ".gv" << endl;

  string command = "dot -Tpdf "+output+".gv  -o "+output+".pdf";
  if (system(command.c_str()) != -1)
    cout << "Created file " << output << ".pdf" << endl;
  else
    cout << "There was an error executing '" << command << "'" << endl;
  return 0;
}

redpajama_set_name: RedPajamaGithub


text:
from __future__ import unicode_literals

from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [
        ('dashboard', '0003_auto_20170113_1853'),
    ]

    operations = [
        migrations.CreateModel(
            name='WhiteList',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('eppn', models.CharField(max_length=100)),
            ],
        ),
    ]


text:
<?php

namespace ZendService\ZendServerAPI\Adapter;

/**
 * AuditMessageDetail Adapter implementation.
 *
 * @license        http://framework.zend.com/license/new-bsd New BSD License
 * @link           http://github.com/zendframework/zf2 for the canonical source repository
 * @author         Ingo Walz <ingo.walz@googlemail.com>
 * @category       Zend
 * @package        Zend_Service
 * @subpackage     ZendServerAPI
 */
class AuditMessageDetails extends Adapter
{
    /**
     * Parse the xml response in object mappings
     *
     * @return \ZendService\ZendServerAPI\DataTypes\DataType
     */
    public function parse ($xml = null)
    {
        if ($xml === null) {
            $xml = $this->getResponse()->getBody();
        }

        $this->setContent($xml);
        $xmlAuditMessage = $this->getElement("//auditMessage");

        $auditMessageDetails = new \ZendService\ZendServerAPI\DataTypes\AuditMessageDetails();

        $auditMessage = new \ZendService\ZendServerAPI\DataTypes\AuditMessage();
        $auditMessage->setId((int) $xmlAuditMessage->id);
        $auditMessage->setUsername((string)$xmlAuditMessage->username);
        $auditMessage->setRequestInterface((string)$xmlAuditMessage->requestInterface);
        $auditMessage->setRemoteAddr((string)$xmlAuditMessage->remoteAddr);
        $auditMessage->setAuditType((string)$xmlAuditMessage->auditType);
        $auditMessage->setAuditTypeTranslated((string)$xmlAuditMessage->auditTypeTranslated);
        $auditMessage->setBaseUrl((string)$xmlAuditMessage->baseUrl);
        $auditMessage->setCreationTime((string)$xmlAuditMessage->creationTime);
        $auditMessage->setCreationTimeTimestramp((string)$xmlAuditMessage->creationTimeTimestamp);
        $auditMessage->setOutcome((string)$xmlAuditMessage->outcome);

        if (isset($xmlAuditMessage->extraData->extraDataMessage)) {

            $extraData = array();
            foreach ($xmlAuditMessage->extraData->extraDataMessage->parameter as $parameter) {
                $extraData[(string)$parameter->name] = (string)$parameter->value;
            }

            $auditMessage->setExtraData($extraData);
        }

        $auditMessageDetails->setAuditMessage($auditMessage);

        $xmlAuditProgressList = $this->getElement("//auditProgressList");

        if (isset($xmlAuditProgressList->auditProgress)) {

            $xmlAuditProgress = $xmlAuditProgressList->auditProgress;
            $auditProgress = new \ZendService\ZendServerAPI\DataTypes\AuditProgress();
            $auditProgress->setProgressId((int)$xmlAuditProgress->progressId);
            $auditProgress->setAuditId((int)$xmlAuditProgress->auditId);
            $auditProgress->setServerId((int)$xmlAuditProgress->serverId);
            $auditProgress->setServerIp((string)$xmlAuditProgress->serverIp);
            $auditProgress->setServerName((string)$xmlAuditProgress->serverName);
            $auditProgress->setCreationTime((string)$xmlAuditProgress->creationTime);
            $auditProgress->setProgress((string)$xmlAuditProgress->progress);

            if (isset($xmlAuditProgress->extraData->extraDataMessage)) {

                $extraData = array();
                foreach ($xmlAuditMessage->extraData->extraDataMessage->parameter as $parameter) {
                    $extraData[(string)$parameter->name] = (string)$parameter->value;
                }

                $auditMessage->setExtraData($extraData);
            }

            $auditMessageDetails->setAuditProgress($auditProgress);
        }

        return $auditMessageDetails;
    }

}


text: assert(isNaN(Number.POSITIVE_INFINITY * 0) === true)


text:
using System;
using System.Linq;
using System.Reflection;
using AutoMapper;

namespace SFA.DAS.EAS.Account.Api.UnitTests.Controllers.AccountTransactionsControllerTests
{
    public abstract class AccountTransactionsControllerTests
    {
        protected IMapper Mapper;

        protected IMapper ConfigureMapper()
        {
            var profiles = Assembly.Load($"SFA.DAS.EAS.Account.Api")
                .GetTypes()
                .Where(t => typeof(Profile).IsAssignableFrom(t))
                .Select(t => (Profile)Activator.CreateInstance(t))
                .ToList();

            var config = new MapperConfiguration(c =>
            {
                profiles.ForEach(c.AddProfile);
            });

            return config.CreateMapper();
        }
    }
}


text:
package com.spotify.heroic.metric;

import java.util.Comparator;

public interface Metric {
    long getTimestamp();

    /**
     * A has implementation that should only take the sample value into account.
     *
     * @return The hash of the sample value.
     */
    int valueHash();

    boolean valid();

    static Comparator<Metric> comparator() {
        return comparator;
    }

    static Metric invalid() {
        return invalid;
    }

    Comparator<Metric> comparator = new Comparator<Metric>() {
        @Override
        public int compare(Metric a, Metric b) {
            return Long.compare(a.getTimestamp(), b.getTimestamp());
        }
    };

    Metric invalid = new Metric() {
        @Override
        public long getTimestamp() {
            throw new IllegalStateException("invalid has not timestamp");
        }

        @Override
        public int valueHash() {
            return 1;
        }

        @Override
        public boolean valid() {
            return false;
        }
    };
}


text:
<meta charset="utf-8"/>
<meta http-equiv="Content-type" content="text/html; charset=utf8"/>
<title>TQuery.slice</title>
<link rel='stylesheet' href='../../css/bootstrap.css'/>
<link rel='stylesheet' href='../../css/tonyu.css'/>

<button onclick='javascript:history.back();'>←Back</button>

TQuery

TQuery.slice メソッド

このTQueryオブジェクトがもつオブジェクトから一部分を切り出した新しいTQueryオブジェクトを返します.

書式はJavaScriptのArrayオブジェクトのsliceメソッドと同じです.

.

<button onclick='javascript:history.back();'>←Back</button>


text:
package net.sf.jabref.logic.layout.format;

import net.sf.jabref.logic.layout.LayoutFormatter;

import org.junit.Before;
import org.junit.Test;

import static org.junit.Assert.assertEquals;

public class RemoveBracketsTest {
    private LayoutFormatter formatter;

    @Before
    public void setUp() {
        formatter = new RemoveBrackets();
    }

    @Test
    public void testFormat() throws Exception {
        assertEquals("some text", formatter.format("{some text}"));
        assertEquals("some text", formatter.format("{some text"));
        assertEquals("some text", formatter.format("some text}"));
        assertEquals("\\some text\\", formatter.format("\\{some text\\}"));
    }
}


text:
package com.quentindommerc.sentencify.utils;

import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONObject;

import com.quentindommerc.sentencify.bean.Album;
import com.quentindommerc.sentencify.bean.Artist;
import com.quentindommerc.sentencify.bean.Track;

public class ApiParser {
	public static Track parseTrack(JSONObject obj) {
		Track t = new Track();
		t.setHref(obj.optString("href"));
		t.setLength(Float.parseFloat(obj.optString("length", "0.0")));
		t.setName(obj.optString("name"));
		t.setPopularity(Float.parseFloat(obj.optString("popularity", "0.0")));
		t.setTrackNumber(Integer.parseInt(obj.optString("track-number", "0")));
		t.setAlbum(ApiParser.parseAlbum(obj.optJSONObject("album")));
		JSONArray artists = obj.optJSONArray("artists");
		if (artists != null)
			for (int i = 0; i < artists.length(); i++) {
				t.addArtist(ApiParser.parseArtist(artists.optJSONObject(i)));
			}
		return t;
	}

	private static Artist parseArtist(JSONObject obj) {
		Artist a = new Artist();
		a.setHref(obj.optString("href"));
		a.setName(obj.optString("name"));
		return a;
	}

	public static Album parseAlbum(JSONObject obj) {
		Album a = new Album();
		a.setHref(obj.optString("href"));
		a.setName(obj.optString("name"));
		a.setReleaseYear(obj.optString("release"));
		JSONObject availability = obj.optJSONObject("availability");
		String[] terr = availability.optString("territories").split(" ");
		ArrayList<String> terrArr = new ArrayList<String>();
		for (String s : terr) {
			terrArr.add(Utils.iso2CountryCodeToIso3CountryCode(s));
		}
		a.setTerritories(terrArr);
		return a;
	}

}


text:
class CreatePosts < ActiveRecord::Migration
  def change
    create_table :posts do |t|
      t.string :title
      t.text :body
      t.string :pic
      t.string :pubdate
      t.integer :mark
      t.integer :viewcount
      t.string :categoryid
      t.string :tagid

      t.timestamps null: false
    end
  end
end


text:
id: ab6137d4e35944e21037b769
title: Title Case a Sentence
isRequired: true
challengeType: 5
videoUrl: ''
localeTitle: العنوان حالة الجملة
---

## Description

 قم بإرجاع السلسلة المتوفرة بالحرف الأول من كل كلمة بالأحرف الكبيرة. تأكد من أن بقية الكلمة في حالة الأحرف الصغيرة. لأغراض هذا التمرين ، يجب أيضًا تكبير الحروف الموصولة مثل "the" و "of". تذكر استخدام Read-Search-Ask إذا واجهتك مشكلة. اكتب الكود الخاص بك.

## Instructions

## Tests

```yml
tests:
  - text: '<code>titleCase("I'm a little tea pot")</code> سلسلة.'
    testString: 'assert(typeof titleCase("I"m a little tea pot") === "string", "<code>titleCase("I'm a little tea pot")</code> should return a string.");'
  - text: '<code>titleCase("I'm a little tea pot")</code> يجب أن أعود <code>I'm A Little Tea Pot</code> .'
    testString: 'assert(titleCase("I"m a little tea pot") === "I"m A Little Tea Pot", "<code>titleCase("I'm a little tea pot")</code> should return <code>I'm A Little Tea Pot</code>.");'
  - text: يجب أن ترجع <code>titleCase("sHoRt AnD sToUt")</code> <code>Short And Stout</code> .
    testString: 'assert(titleCase("sHoRt AnD sToUt") === "Short And Stout", "<code>titleCase("sHoRt AnD sToUt")</code> should return <code>Short And Stout</code>.");'
  - text: <code>titleCase("HERE IS MY HANDLE HERE IS MY SPOUT")</code> <code>Here Is My Handle Here Is My Spout</code> <code>titleCase("HERE IS MY HANDLE HERE IS MY SPOUT")</code> يجب أن يعود <code>Here Is My Handle Here Is My Spout</code> .
    testString: 'assert(titleCase("HERE IS MY HANDLE HERE IS MY SPOUT") === "Here Is My Handle Here Is My Spout", "<code>titleCase("HERE IS MY HANDLE HERE IS MY SPOUT")</code> should return <code>Here Is My Handle Here Is My Spout</code>.");'

```

## Challenge Seed

```js
function titleCase(str) {
  return str;
}

titleCase("I'm a little tea pot");

```

## Solution

```js
// solution required
```


text:
@interface AppDelegate ()

@end

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

    [GJRedDot registWithProfile:[GJRedDotRegister registProfiles] defaultShow:YES];
    [GJRedDot setDefaultRadius:4];
    [GJRedDot setDefaultColor:[UIColor orangeColor]];
    //set tab bar item icon
    UITabBarController *tabVC = (UITabBarController*)self.window.rootViewController;
    UITabBarItem *item2 = tabVC.tabBar.items[1];
    [item2 setImage:[[UIImage imageNamed:@"tabIcon"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal]];

    //set tab bar item red dot
    [self setRedDotKey:GJTabBar2 refreshBlock:^(BOOL show) {
        item2.showRedDot = show;
    } handler:self];

    return YES;
}

- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

@end


text:
package com.github.spirom.sparkflights.experiments

import com.github.spirom.sparkflights.fw.SQLExperiment
import org.apache.spark.sql.SQLContext

class TopAirportsByCancellationsSQL(sqlContext: SQLContext)
  extends SQLExperiment("TopAirportsByCancellationsSQL", sqlContext) {

  def runUserCode(sqlContext: SQLContext, outputBase: String): Unit = {

    //
    // The 10 origin airports with the highest absolute number
    // of departure cancellations since 2000
    //

    val popularFlights = sqlContext.sql(
      s"""
        | SELECT origin, count(cancelled) AS total_cancellations
        | FROM flights
        | WHERE cancelled = '1' AND year >= '2000'
        | GROUP BY origin
        | ORDER BY total_cancellations DESC
        | LIMIT 10
       """.stripMargin)
    popularFlights.rdd.saveAsTextFile(s"$outputBase/top_cancellations")
  }

}


text:
goog.provide('app.interactiontoggle');

goog.require('ngeo.DecorateInteraction');
/** @suppress {extraRequire} */
goog.require('ngeo.mapDirective');
goog.require('ol.Map');
goog.require('ol.View');
goog.require('ol.interaction.Draw');
goog.require('ol.layer.Tile');
goog.require('ol.layer.Vector');
goog.require('ol.source.OSM');
goog.require('ol.source.Vector');

/** @type {!angular.Module} **/
const module = angular.module('app', ['ngeo']);

/**
 * @param {ngeo.DecorateInteraction} ngeoDecorateInteraction Decorate
 *     interaction service.
 * @constructor
 * @ngInject
 */
app.MainController = function(ngeoDecorateInteraction) {

  /**
   * @type {ol.Map}
   * @export
   */
  this.map = new ol.Map({
    layers: [
      new ol.layer.Tile({
        source: new ol.source.OSM()
      })
    ],
    view: new ol.View({
      center: [-10997148, 4569099],
      zoom: 4
    })
  });

  const map = this.map;

  const vectorLayer = new ol.layer.Vector({
    source: new ol.source.Vector()
  });

  // Use vectorLayer.setMap(map) rather than map.addLayer(vectorLayer). This
  // makes the vector layer "unmanaged", meaning that it is always on top.
  vectorLayer.setMap(map);

  /**
   * @type {ol.interaction.Draw}
   * @export
   */
  this.interaction = new ol.interaction.Draw(
      /** @type {olx.interaction.DrawOptions} */ ({
        type: 'Point',
        source: vectorLayer.getSource()
      }));

  const interaction = this.interaction;
  interaction.setActive(false);
  map.addInteraction(interaction);
  ngeoDecorateInteraction(interaction);

};

module.controller('MainController', app.MainController);


text:
var HIBANA = {

	age: function () { HIBANA.Emitters.all( "age" ); },

	Emitters: {

		ref: [],

		all: function ( method_name, arg ) {
			for ( e in HIBANA.Emitters.ref )
				HIBANA.Emitters.ref[e][method_name]( arg );
		},

		add: function ( object, parameters ) {
			var new_emitter = new HIBANA.Emitter( object, parameters );
			HIBANA.Emitters.ref.push( new_emitter );
			return new_emitter;
		},

		setDefaultParameters: function ( parameters ) {
			for ( p in parameters )
				HIBANA.Emitters._default_parameters[p] = HIBANA._clone( parameters[p] );
		},

		_default_parameters: {
			paused: true,
			spawn:	new HIBANA.Event( 0.75, new HIBANA.Range(.05, .4)),
			behavior_mods:  [],
			angle:	0.0,
			hidden_point:	new THREE.Vector3( -1000, -1000, -1000 )
		}
	},

	Universal:	{

		acceleration: new THREE.Vector3( 0.0, -0.000985, 0.0 ),

		is_active: false,

		set: function( acceleration ) { HIBANA.Universal.acceleration = acceleration; },

		add: function( acceleration ) { HIBANA.Universal.acceleration.addSelf( acceleration ); },

		remove: function( acceleration ) { HIBANA.Universal.acceleration.subSelf( acceleration ); },

		activate: function() { HIBANA.Universal.is_active = true; },

		deactivate: function() { HIBANA.Universal.is_active = false; },

		toggle: function() { HIBANA.Universal.is_active = !HIBANA.Universal.is_active; }
	}
};


text:
<vars xmlns="http://www.idiominc.com/opentopic/vars">
  <variable id="blank_page">This page intentionally left blank</variable>
  <variable id="#table-continued">Table continued…</variable>
  <variable id="Figure"><param ref-name="title"/></variable>
  <variable id="Table"><param ref-name="title"/></variable>
  <variable id="Chapter with number"></variable>
  <variable id="Table of Contents Chapter"></variable>
  <variable id="Table of Contents Appendix">Appendix: </variable>
</vars>


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Die Blätterpilze 332 (1914)

#### Original name
Agaricus aurantia Schaeff.

### Remarks
null


text:
namespace fcp {
namespace secagg {
namespace {

using ::testing::Eq;

// For testing purposes, make an AesKey out of a string.
AesKey AesKeyFromString(const std::string& key) {
  return AesKey(reinterpret_cast<const uint8_t*>(key.c_str()),
                static_cast<int>(key.size()));
}

// Suppose the randomly chosen key can be expressed in bit_length <= 128 bits.
// Java did not express the key in 128 bits, but rather will have used
// (bit_length + 1) bits. The extra bit is the highest-order bit, and is a sign
// bit, guaranteed to be 0. The next highest-order bit is guaranteed to be 1.
std::string JavaStyleKey(int bit_length) {
  EXPECT_TRUE(0 < bit_length && bit_length <= 128);
  std::string key = "16 byte test key";
  int byte_with_sign_bit = (127 - bit_length) / 8;
  int pos_of_sign_bit = (127 - bit_length) % 8;
  if (bit_length == 128) {
    pos_of_sign_bit = 7;
    key = absl::StrCat("\0", key);
  } else {
    key.erase(0, byte_with_sign_bit);
  }
  // Make sure the high-order bit is the sign bit 0, and the next highest-order
  // bit is 1.
  key[0] = static_cast<char>(127 >> pos_of_sign_bit);
  if (pos_of_sign_bit == 7) {
    key[1] = static_cast<char>(255);
  }
  return key;
}

TEST(AesKeyTest, CreateFromSharesHandles32BKeys) {
  AesKey original_key = AesKeyFromString("32 byte AES key for testing only");
  ShamirSecretSharing shamir;
  auto shares = shamir.Share(5, 7, original_key);
  auto key_or_error = AesKey::CreateFromShares(shares, 5);
  EXPECT_THAT(key_or_error.ok(), Eq(true));
  EXPECT_THAT(key_or_error.value(), Eq(original_key));
}

TEST(AesKeyTest, CreateFromSharesHandlesShortKeys) {
  ShamirSecretSharing shamir;
  for (int i = 1; i <= 128; ++i) {
    std::string original_key_string = JavaStyleKey(i);
    AesKey original_key = AesKeyFromString(original_key_string);
    std::string key_string_for_sharing;
    if (original_key_string.size() < 16) {
      key_string_for_sharing =
          absl::StrCat(std::string(16 - original_key_string.size(), '\0'),
                       original_key_string);
    } else if (original_key_string.size() == 17) {
      key_string_for_sharing = original_key_string.substr(1);
    } else {
      key_string_for_sharing = original_key_string;
    }
    auto shares = shamir.Share(5, 7, AesKeyFromString(key_string_for_sharing));
    auto key_or_error = AesKey::CreateFromShares(shares, 5);
    EXPECT_THAT(key_or_error.ok(), Eq(true));
    EXPECT_THAT(key_or_error.value(), Eq(original_key))
        << i << " bit key fails";
  }
}

}  // namespace
}  // namespace secagg
}  // namespace fcp


text:
/* eslint-disable no-func-assign */

'use strict';

let React;
let ReactNoop;
let Scheduler;
let act;
let useEffect;
let useLayoutEffect;

describe('ReactHooksWithNoopRenderer', () => {
  beforeEach(() => {
    jest.resetModules();
    jest.useFakeTimers();

    React = require('react');
    ReactNoop = require('react-noop-renderer');
    Scheduler = require('scheduler');
    act = require('jest-react').act;
    useEffect = React.useEffect;
    useLayoutEffect = React.useLayoutEffect;
  });

  test('layout unmmouts on deletion are fired in parent -> child order', async () => {
    const root = ReactNoop.createRoot();

    function Parent() {
      useLayoutEffect(() => {
        return () => Scheduler.unstable_yieldValue('Unmount parent');
      });
      return <Child />;
    }

    function Child() {
      useLayoutEffect(() => {
        return () => Scheduler.unstable_yieldValue('Unmount child');
      });
      return 'Child';
    }

    await act(async () => {
      root.render(<Parent />);
    });
    expect(root).toMatchRenderedOutput('Child');
    await act(async () => {
      root.render(null);
    });
    expect(Scheduler).toHaveYielded(['Unmount parent', 'Unmount child']);
  });

  test('passive unmmouts on deletion are fired in parent -> child order', async () => {
    const root = ReactNoop.createRoot();

    function Parent() {
      useEffect(() => {
        return () => Scheduler.unstable_yieldValue('Unmount parent');
      });
      return <Child />;
    }

    function Child() {
      useEffect(() => {
        return () => Scheduler.unstable_yieldValue('Unmount child');
      });
      return 'Child';
    }

    await act(async () => {
      root.render(<Parent />);
    });
    expect(root).toMatchRenderedOutput('Child');
    await act(async () => {
      root.render(null);
    });
    expect(Scheduler).toHaveYielded(['Unmount parent', 'Unmount child']);
  });
});


text:
package Simly.core;

public class SimlyObject {

	private SimlyObject parent  = null;

	public SimlyObject()
	{

	}

	public SimlyObject (SimlyObject parent)
	{
		this.parent = parent;
	}

	public SimlyObject getParent()
	{
		return parent;
	}
}


text:
layout: post
title: "Dealing with EBS volume hotplug"
description: "EBS volumes are hotplugged. They may need formatting. And your service can't start until the volume is ready, so the default init scripts just won't cut it"
category: Amazon
tags: ['amazon', 'aws', 'ebs', 'ec2', 'volume', 'storage', 'upstart', 'init', 'trusty', 'ubuntu']
---

EBS volumes are attached to EC2 instances that are running. So if you have a solr instance that starts on boot and needs to use that EBS volume you have a problem. How do you make solr wait for that EBS volume to be ready? How do you format it? How do you make all this idempotent.

On Linux, `udev` is how we get notified of a block device getting plugged in. One option that has popped up is [ebsmount](https://www.turnkeylinux.org/blog/ebsmount) which uses [custom udev rules](https://github.com/turnkeylinux/ebsmount/blob/master/85-ebsmount.rules.in) to run your code when a new EBS volume is attached. However on Ubuntu Trusty we have upstart. Upstart has a udev bridge and so we can start a service or run a task in response to the event:

```
start on block-device-added DEVNAME='/dev/xvdf'
task
script
    if [ ! "`blkid /dev/xvdf -o value -s TYPE -c /dev/null`" = "ext4" ]
    then
        mkfs -t ext4 /dev/xvdf
    fi
    if [ ! -d /data ]; then
        echo "/data does not exist. creating..."
        mkdir /data
    fi
    mount /dev/xvdf /data
    initctl emit path-mounted device=/dev/xvdf path=/data
end script
```

We use `blkid` to check if the EBS volume is formatted as `ext4`. If it's not then it soon will be. And then when it's formatted we can mount it. The internet aludes to an upstart event type called `path-mounted` that we would use to start solr when `/data` was mounted. This doesn't seem to work - you can work around it and generate it manually with `initctl emit`.

Then the solr init script is replaced with:

```
start on path-mounted path=/data
env JAVA_HOME="/usr/lib/jvm/java-7-openjdk-amd64"

pre-start script
    if [ ! -d /data/solr ]; then
        mkdir /data/solr
        chown jetty: /data/solr
    fi
end-script

exec /usr/bin/jsvc \
    -nodetach \
    -user jetty \
    <...> \
    -Djetty.host=0.0.0.0 \
    -Djetty.port=8983
```

I totally remove `/etc/init.d/jetty` and add a new upstart configuration - having `/etc/init.d/jetty` and `/etc/init/jetty.conf` seems to cause `sudo start jetty` and `sudo stop jetty` to hang. Just start solr with `/etc/init.d/jetty start` and grap the right command line with `ps aux`. Stick in a `-nodetach` to stop in forking so it plays nice with upstarts process supervision. This also gives us a nice place to create `/data/solr` and ensure its writeable by the `jetty` user.

Don't forget to update `solr.xml` to point at this new location! :wink:


text:
package com.percero.amqp;

import com.percero.agents.sync.access.IAccessManager;
import com.percero.agents.sync.cw.CheckChangeWatcherMessage;
import com.percero.agents.sync.vo.BaseDataObject;
import org.apache.log4j.Logger;
import org.codehaus.jackson.JsonNode;
import org.codehaus.jackson.map.ObjectMapper;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * Created by jonnysamps on 11/23/15.
 */
@Component("checkChangeWatcherListener")
public class CheckChangeWatcherListener implements MessageListener {

    private static Logger logger = Logger.getLogger(CheckChangeWatcherListener.class);

    @Autowired
    ObjectMapper om;

    @Autowired
    IAccessManager accessManager;
    public void setAccessManager(IAccessManager value) {
        accessManager = value;
    }

    @Override
    public void onMessage(Message message) {
        try {
            JsonNode node = om.readTree(message.getBody());
            CheckChangeWatcherMessage checkChangeWatcherMessage = om.readValue(node, CheckChangeWatcherMessage.class);
            BaseDataObject oldValue = getDeserializeOldValue(checkChangeWatcherMessage.classIDPair.getClassName(),
                    checkChangeWatcherMessage.oldValueJson);
            accessManager.checkChangeWatchers(checkChangeWatcherMessage.classIDPair,
                    checkChangeWatcherMessage.fieldNames,
                    checkChangeWatcherMessage.params,
                    oldValue);
        }catch(Exception e){
            logger.error(e.getMessage(), e);
        }
    }

    private BaseDataObject getDeserializeOldValue(String className, String json){
        if(json == null) return null;

        BaseDataObject result = null;

        try {
            Class clazz = Class.forName(className);
            result = (BaseDataObject) clazz.newInstance();
            result.fromJson(json);
        }catch(Exception e){ logger.error(e.getMessage(), e); }

        return result;
    }
}


text:
--------------------------------
-- @function [parent=#SpriteFrame] setRotated
-- @param self
-- @param #bool bool

--------------------------------
-- @function [parent=#SpriteFrame] setTexture
-- @param self
-- @param #cc.Texture2D texture2d

--------------------------------
-- overload function: initWithTexture(cc.Texture2D, rect_table, bool, point_table, size_table)
--
-- overload function: initWithTexture(cc.Texture2D, rect_table)
--
-- @function [parent=#SpriteFrame] initWithTexture
-- @param self
-- @param #cc.Texture2D texture2d
-- @param #rect_table rect
-- @param #bool bool
-- @param #point_table point
-- @param #size_table size
-- @return bool#bool ret (retunr value: bool)

--------------------------------
-- @function [parent=#SpriteFrame] setRectInPixels
-- @param self
-- @param #rect_table rect

--------------------------------
-- @function [parent=#SpriteFrame] getTexture
-- @param self
-- @return Texture2D#Texture2D ret (return value: cc.Texture2D)

--------------------------------
-- @function [parent=#SpriteFrame] getRect
-- @param self
-- @return rect_table#rect_table ret (return value: rect_table)

--------------------------------
-- @function [parent=#SpriteFrame] setOffsetInPixels
-- @param self
-- @param #point_table point

--------------------------------
-- @function [parent=#SpriteFrame] getRectInPixels
-- @param self
-- @return rect_table#rect_table ret (return value: rect_table)

--------------------------------
-- @function [parent=#SpriteFrame] setOriginalSize
-- @param self
-- @param #size_table size

--------------------------------
-- @function [parent=#SpriteFrame] getOriginalSizeInPixels
-- @param self
-- @return size_table#size_table ret (return value: size_table)

--------------------------------
-- @function [parent=#SpriteFrame] setOriginalSizeInPixels
-- @param self
-- @param #size_table size

--------------------------------
-- @function [parent=#SpriteFrame] setOffset
-- @param self
-- @param #point_table point

--------------------------------
-- @function [parent=#SpriteFrame] getOffset
-- @param self
-- @return point_table#point_table ret (return value: point_table)

--------------------------------
-- @function [parent=#SpriteFrame] isRotated
-- @param self
-- @return bool#bool ret (return value: bool)

--------------------------------
-- overload function: initWithTextureFilename(string, rect_table, bool, point_table, size_table)
--
-- overload function: initWithTextureFilename(string, rect_table)
--
-- @function [parent=#SpriteFrame] initWithTextureFilename
-- @param self
-- @param #string str
-- @param #rect_table rect
-- @param #bool bool
-- @param #point_table point
-- @param #size_table size
-- @return bool#bool ret (retunr value: bool)

--------------------------------
-- @function [parent=#SpriteFrame] setRect
-- @param self
-- @param #rect_table rect

--------------------------------
-- @function [parent=#SpriteFrame] getOffsetInPixels
-- @param self
-- @return point_table#point_table ret (return value: point_table)

--------------------------------
-- @function [parent=#SpriteFrame] getOriginalSize
-- @param self
-- @return size_table#size_table ret (return value: size_table)

--------------------------------
-- overload function: create(string, rect_table, bool, point_table, size_table)
--
-- overload function: create(string, rect_table)
--
-- @function [parent=#SpriteFrame] create
-- @param self
-- @param #string str
-- @param #rect_table rect
-- @param #bool bool
-- @param #point_table point
-- @param #size_table size
-- @return SpriteFrame#SpriteFrame ret (retunr value: cc.SpriteFrame)

--------------------------------
-- overload function: createWithTexture(cc.Texture2D, rect_table, bool, point_table, size_table)
--
-- overload function: createWithTexture(cc.Texture2D, rect_table)
--
-- @function [parent=#SpriteFrame] createWithTexture
-- @param self
-- @param #cc.Texture2D texture2d
-- @param #rect_table rect
-- @param #bool bool
-- @param #point_table point
-- @param #size_table size
-- @return SpriteFrame#SpriteFrame ret (retunr value: cc.SpriteFrame)

return nil


text:
class ThreadStore;
typedef DPTR(ThreadStore) PTR_ThreadStore;
class Module;
typedef DPTR(Module) PTR_Module;
class ICodeManager;
struct GenericInstanceDesc;
typedef SPTR(GenericInstanceDesc) PTR_GenericInstanceDesc;
struct ModuleHeader;
enum GenericVarianceType : UInt8;
struct UnifiedGenericInstance;
class GenericTypeHashTable;
typedef DPTR(GenericTypeHashTable) PTR_GenericTypeHashTable;
struct StaticGcDesc;

class RuntimeInstance
{
    friend class AsmOffsets;
    friend struct DefaultSListTraits<RuntimeInstance>;
    friend class Thread;

    PTR_RuntimeInstance         m_pNext;
    PTR_ThreadStore             m_pThreadStore;
    HANDLE                      m_hPalInstance; // this is the HANDLE passed into DllMain
    SList<Module>               m_ModuleList;
    ReaderWriterLock            m_ModuleListLock;

#ifdef FEATURE_DYNAMIC_CODE
    struct CodeManagerEntry;
    typedef DPTR(CodeManagerEntry) PTR_CodeManagerEntry;

    struct CodeManagerEntry
    {
        PTR_CodeManagerEntry    m_pNext;
        PTR_VOID                m_pvStartRange;
        UInt32                  m_cbRange;
        ICodeManager *          m_pCodeManager;
    };

    typedef SList<CodeManagerEntry> CodeManagerList;
    CodeManagerList             m_CodeManagerList;
#endif

    // Indicates whether the runtime is in standalone exe mode where the only Redhawk module that will be
    // loaded into the process (besides the runtime's own module) is the exe itself. This flag will be
    // correctly initialized once the exe module has loaded.
    bool                        m_fStandaloneExeMode;

    // If m_fStandaloneExeMode is set this contains a pointer to the exe module. Otherwise it's null.
    Module *                    m_pStandaloneExeModule;

#ifdef FEATURE_PROFILING
    // The thread writing the profile data is created lazily, whenever
    // a module with a profile section is registered.
    // To avoid starting the thread more than once, this flag indicates
    // whether the thread has been created already.
    bool                        m_fProfileThreadCreated;
#endif

    // List of generic instances that have GC references to report. This list is updated under the hash table
    // lock above and enumerated without lock during garbage collections (when updates cannot occur). This
    // list is only used in non-standalone exe mode, i.e. when we're unifying generic types. In standalone
    // mode we report the GenericInstanceDescs directly from the module itself.
    PTR_GenericInstanceDesc     m_genericInstReportList;

    ReaderWriterLock            m_GenericHashTableLock;

    // This is used (in standalone mode only) to build an on-demand hash tables of all generic instantiations
    PTR_GenericTypeHashTable            m_pGenericTypeHashTable;

    bool                        m_conservativeStackReportingEnabled;

    RuntimeInstance();

    SList<Module>* GetModuleList();

    bool BuildGenericTypeHashTable();

public:
    class ModuleIterator
    {
        ReaderWriterLock::ReadHolder    m_readHolder;
        PTR_Module                      m_pCurrentPosition;
    public:
        ModuleIterator();
        ~ModuleIterator();
        PTR_Module GetNext();
    };

    ~RuntimeInstance();
    ThreadStore *   GetThreadStore();
    HANDLE          GetPalInstance();

    bool RegisterModule(ModuleHeader *pModuleHeader);
    void UnregisterModule(Module *pModule);
    Module * FindModuleByAddress(PTR_VOID pvAddress);
    Module * FindModuleByCodeAddress(PTR_VOID ControlPC);
    Module * FindModuleByDataAddress(PTR_VOID Data);
    Module * FindModuleByReadOnlyDataAddress(PTR_VOID Data);
    Module * FindModuleByOsHandle(HANDLE hOsHandle);
    PTR_UInt8 FindMethodStartAddress(PTR_VOID ControlPC);
    bool EnableConservativeStackReporting();
    bool IsConservativeStackReportingEnabled() { return m_conservativeStackReportingEnabled; }

#ifdef FEATURE_DYNAMIC_CODE
    bool RegisterCodeManager(ICodeManager * pCodeManager, PTR_VOID pvStartRange, UInt32 cbRange);
    void UnregisterCodeManager(ICodeManager * pCodeManager);
#endif
    ICodeManager * FindCodeManagerByAddress(PTR_VOID ControlPC);

    // This will hold the module list lock over each callback. Make sure
    // the callback will not trigger any operation that needs to make use
    // of the module list.
    typedef void (* EnumerateModulesCallbackPFN)(Module *pModule, void *pvContext);
    void EnumerateModulesUnderLock(EnumerateModulesCallbackPFN pCallback, void *pvContext);

    static  RuntimeInstance *   Create(HANDLE hPalInstance);
    void Destroy();

    void EnumGenericStaticGCRefs(PTR_GenericInstanceDesc pInst, void * pfnCallback, void * pvCallbackData, Module *pModule);
    void EnumAllStaticGCRefs(void * pfnCallback, void * pvCallbackData);

    bool ShouldHijackCallsiteForGcStress(UIntNative CallsiteIP);
    bool ShouldHijackLoopForGcStress(UIntNative CallsiteIP);

    void EnableGcPollStress();
    void UnsychronizedResetHijackedLoops();

    // Given the EEType* for an instantiated generic type retrieve the GenericInstanceDesc associated with
    // that type. This is legal only for types that are guaranteed to have this metadata at runtime; generic
    // types which have variance over one or more of their type parameters and generic interfaces on array).
    GenericInstanceDesc * LookupGenericInstance(EEType * pEEType);

    // Given the EEType* for an instantiated generic type retrieve instantiation information (generic type
    // definition EEType, arity, type arguments and variance info for each type parameter). Has the same
    // limitations on usage as LookupGenericInstance above.
    EEType * GetGenericInstantiation(EEType *               pEEType,
                                     UInt32 *               pArity,
                                     EEType ***             ppInstantiation,
                                     GenericVarianceType ** ppVarianceInfo);

    bool SetGenericInstantiation(EEType *               pEEType,
                                 EEType *               pEETypeDef,
                                 UInt32                 arity,
                                 EEType **              pInstantiation);

    bool CreateGenericInstanceDesc(EEType *             pEEType,
                                   EEType *             pTemplateType,
                                   UInt32               arity,
                                   UInt32               nonGcStaticDataSize,
                                   UInt32               nonGCStaticDataOffset,
                                   UInt32               gcStaticDataSize,
                                   UInt32               threadStaticOffset,
                                   StaticGcDesc *       pGcStaticsDesc,
                                   StaticGcDesc *       pThreadStaticsDesc,
                                   UInt32*              pGenericVarianceFlags);

#ifdef FEATURE_PROFILING
    void InitProfiling(ModuleHeader *pModuleHeader);
    void WriteProfileInfo();
#endif // FEATURE_PROFILING

    bool IsInStandaloneExeMode()
    {
        return m_fStandaloneExeMode;
    }

    Module * GetStandaloneExeModule()
    {
        ASSERT(IsInStandaloneExeMode());
        return m_pStandaloneExeModule;
    }
};
typedef DPTR(RuntimeInstance) PTR_RuntimeInstance;

PTR_RuntimeInstance GetRuntimeInstance();

#define FOREACH_MODULE(p_module_name)                       \
{                                                           \
    RuntimeInstance::ModuleIterator __modules;              \
    Module * p_module_name;                                 \
    while ((p_module_name = __modules.GetNext()) != NULL)   \
    {                                                       \

#define END_FOREACH_MODULE  \
    }                       \
}                           \


text:
@var area = getAllArea(); //全部区域

机构名称

			${office.name!}

机构类型

			${dict.getDictByTypeAndValue("sys_office_type",office.type).label}

上级机构

			${pOffice.name!}

归属区域

			${area[office.areaId].name!}

图标

负责人

			${office.master!}

电话

			${office.phone!}

邮箱

			${office.email!}

联系地址

			${office.address!}

邮政编码

			${office.zip_code!}

传真

			${office.fax!}

创建者

			${office.createBy!}

创建时间

			${office.createDate!}

更新者

			${office.updateBy!}

更新时间

			${office.updateDate!}

备注

			${office.remarks!}


text:
<?php

/*
 * Contains functions to facilitate the search module.
 *
 * Author: Costa
 *
 * Rank Query SELECT statements adapted from:
 * http://stackoverflow.com/questions/8352796/ora-29908-missing-primary-invocation-for-ancillary-operator
 * Author: Paul Kar.
 * Date: 3/22/15
 */

/*
 * Verifies that the user's input into the search module form is vaild.
 */
function verifyInput($keywords, $ordering, $start_date, $end_date, $pattern) {
    if ($keywords == '' and $ordering == 'rank') {
        echo 'Cannot search by relevance without keywords.
';
        echo 'Back';
        return false;
    } else if ($keywords == '' and $start_date == '' and $end_date == '') {
        echo 'Please enter search keywords and/or time period to search.
';
        echo 'Back';
    } else if (($start_date == '') and ( $end_date != '')) {
        echo 'Please enter a start date.
';
        echo 'Back';
        return false;
    } else if (($start_date != '') and ( $end_date == '')) {
        echo 'Please enter an end date.
';
        echo 'Back';
        return false;
    } else if ($start_date != '' and ! preg_match($pattern, $start_date)) {
        echo 'Please enter a valid start date.
';
        echo 'Back';
        return false;
    } else if ($end_date != '' and ! preg_match($pattern, $end_date)) {
        echo 'Please enter a valid end date.
';
        echo 'Back';
        return false;
    } else {
        return true;
    }
}

/*
 * Generates the appropriate search query depending on the user's input into
 * the search module.
 */
function generateSearchQuery($userType, $person_id, $keywords, $ordering, $time_ref, $start_date, $end_date) {

    // Keywords used
    if ($keywords != '') {
        $sql = "SELECT rr.record_id, rs.patient_name, "
                . "pd.first_name || ' ' || pd.last_name AS doc_name, "
                . "pr.first_name || ' ' || pr.last_name AS rad_name, "
                . "rr.test_type, rr.prescribing_date, rr.test_date, rr.diagnosis, rr.description, rs.rank "
                . "FROM radiology_record rr, persons pd, persons pr, "
                . "(SELECT record_id, 6*SCORE(1) + 3*SCORE(2) + SCORE(3) AS rank, patient_name "
                . "FROM radiology_search "
                . "WHERE  CONTAINS(patient_name, '" . $keywords . "', 1)>0 "
                . "OR CONTAINS(diagnosis, '" . $keywords . "', 2)>0 "
                . "OR CONTAINS(description, '" . $keywords . "', 3)>0 "
                . ") rs "
                . "WHERE rr.record_id = rs.record_id "
                . "AND rr.doctor_id = pd.person_id "
                . "AND rr.radiologist_id = pr.person_id ";
        // Keywords and time period
        if ($start_date != '' and $time_ref == 't_date') {
            $sql .= "AND rr.test_date >= TO_DATE('" . $start_date . "','yyyy-mm-dd') "
                    . "AND rr.test_date <= TO_DATE('" . $end_date . "','yyyy-mm-dd') ";
        } else if ($start_date != '' and $time_ref == 'p_date') {
            $sql .= "AND rr.prescribing_date >= TO_DATE('" . $start_date . "','yyyy-mm-dd') "
                    . "AND rr.prescribing_date <= TO_DATE('" . $end_date . "','yyyy-mm-dd') ";
        }
    }
    // Time period only
    else {
        $sql = "SELECT rr.record_id, "
                . "pp.first_name || ' ' || pp.last_name AS patient_name, "
                . "pd.first_name || ' ' || pd.last_name AS doc_name, "
                . "pr.first_name || ' ' || pr.last_name AS rad_name, "
                . "rr.test_type, rr.prescribing_date, rr.test_date, rr.diagnosis, rr.description "
                . "FROM   radiology_record rr, persons pd, persons pr, persons pp "
                . "WHERE rr.doctor_id = pd.person_id "
                . "AND rr.radiologist_id = pr.person_id "
                . "AND rr.patient_id = pp.person_id ";
        if ($start_date != '' and $time_ref == 't_date') {
            $sql .= "AND rr.test_date >= TO_DATE('" . $start_date . "','yyyy-mm-dd') "
                    . "AND rr.test_date <= TO_DATE('" . $end_date . "','yyyy-mm-dd') ";
        } else if ($start_date != '' and $time_ref == 'p_date') {
            $sql .= "AND rr.prescribing_date >= TO_DATE('" . $start_date . "','yyyy-mm-dd') "
                    . "AND rr.prescribing_date <= TO_DATE('" . $end_date . "','yyyy-mm-dd') ";
        }
    }

    // Security check
    if ($userType == 'p') {
        $sql .= "AND rr.patient_id = ".$person_id;
    } else if ($userType == 'r') {
        $sql .= "AND rr.radiologist_id = ".$person_id;
    } else if ($userType == 'd') {
        $sql .= "AND rr.patient_id IN (SELECT patient_id "
                . "FROM family_doctor "
                . "WHERE doctor_id = ".$person_id.")";
    }

    // Ordering
    if ($ordering == 'rank') {
        $sql .= " ORDER BY rs.rank";
    } else if ($ordering == 'time_new' and $time_ref == 't_date') {
        $sql .= " ORDER BY rr.test_date DESC";
    } else if ($ordering == 'time_new' and $time_ref == 'p_date') {
        $sql .= " ORDER BY rr.prescribing_date DESC";
    } else if ($ordering == 'time_old' and $time_ref == 't_date') {
        $sql .= " ORDER BY rr.test_date";
    } else if ($ordering == 'time_old' and $time_ref == 'p_date') {
        $sql .= " ORDER BY rr.prescribing_date";
    }
    //echo $sql;
    return $sql;
}

?>


text:
goutteSVGDrawer = {

  drawGoutte: function() {

    var goutteWrapper = d3.select('#goutte-wrapper');

    d3.xml("img/goutte/fond_goutte.svg", "image/svg+xml", function(xml) {
      var importedNode = document.importNode(xml.documentElement, true);
      goutteWrapper.node().appendChild(importedNode);

      // AMMONIUM
      d3.xml("img/goutte/intern.svg", "image/svg+xml", function(xml) {

        var importedNode = document.importNode(xml.documentElement, true);
        goutteWrapper.node().appendChild(importedNode);

        function changeDescriptionText (idText) {
          var elements = document.querySelectorAll('.explication');
          for (var i = 0; i < elements.length; i++) {
            elements[i].style.display = 'none';
          };
          var element = document.getElementById(idText);
          clearTimeout(timer);
          element.style.display = 'block';
          var opacityValue = 0;
          var timer;
          for (var k = 1; k <= 100; k++) {
            var timer = setTimeout((function (x) {
              return function () {
                opacityValue++;
                element.style.opacity = opacityValue / 100;
              };
            })(k), k * 10);
          }
        }

        var element = document.getElementById('ammonium-path');
        var box = element.getBBox();
        var maxScaleVal = 1.32;
        var scaleVal = 1;
        var norme = 0.04

        // find scaleValue
        if ($scope.city.attributes.ammonium > norme) {
          scaleVal = ((($scope.city.attributes.ammonium / norme) - 1) * (maxScaleVal - 1)) + 1;
          scaleVal = scaleVal > maxScaleVal ? maxScaleVal : scaleVal;
        } else {
          scaleVal = $scope.city.attributes.ammonium / norme;
        }

        // reajust data on la goutte
        var cx = box.x + box.width;
        var cy = box.y + box.height;
        element.setAttribute('transform', 'translate(' + cx + ' ' + cy + ') scale(' + scaleVal + ') translate(' + (-cx) + ' ' + (-cy) + ')');

        // CHLORE
        var element = document.getElementById('chlore-path');
        var box = element.getBBox();
        var maxScaleVal = 1.3;
        var scaleVal =1;
        var norme = 0.10;

        // find scaleValue
        if ($scope.city.attributes.chlore > norme) {
          scaleVal = ((($scope.city.attributes.chlore / norme) - 1) * (maxScaleVal - 1)) + 1;
          scaleVal = scaleVal > maxScaleVal ? maxScaleVal : scaleVal;
        } else {
          scaleVal = $scope.city.attributes.chlore / norme;
        }

        // reajust data on la goutte
        var cx = box.x;
        var cy = box.y + box.height;
        element.setAttribute('transform', 'translate(' + cx + ' ' + cy + ') scale(' + scaleVal + ') translate(' + (-cx) + ' ' + (-cy) + ')');

      // CONDUCTIVITE
        var element = document.getElementById('conductivite-path');
        var box = element.getBBox();
        var maxScaleVal = 1.35;
        var scaleVal = 1;
        var norme = 600;

        // find scaleValue
        if ($scope.city.attributes.conductivite > norme) {
          scaleVal = ((($scope.city.attributes.conductivite / norme) - 1) * (maxScaleVal - 1)) + 1;
          scaleVal = scaleVal > maxScaleVal ? maxScaleVal : scaleVal;
        } else {
          scaleVal = $scope.city.attributes.conductivite / norme;
        }

        // reajust data on la goutte
        var cx = box.x;
        var cy = 222.4;
        element.setAttribute('transform', 'translate(' + cx + ' ' + cy + ') scale(' + scaleVal + ') translate(' + (-cx) + ' ' + (-cy) + ')');

        // NITRATES
        var element = document.getElementById('nitrates-path');
        var box = element.getBBox();
        var maxScaleVal = 1.50;
        var scaleVal = 1;
        var norme = 50;

        // find scaleValue
        if ($scope.city.attributes.nitrates > norme) {
          scaleVal = ((($scope.city.attributes.nitrates / norme) - 1) * (maxScaleVal - 1)) + 1;
          scaleVal = scaleVal > maxScaleVal ? maxScaleVal : scaleVal;
        } else {
          scaleVal = $scope.city.attributes.nitrates / norme;
        }

        // reajust data on la goutte
        var cx = 203.7;
        var cy = box.y;
        element.setAttribute('transform', 'translate(' + cx + ' ' + cy + ') scale(' + scaleVal + ') translate(' + (-cx) + ' ' + (-cy) + ')');

        // PH
        var element = document.getElementById('ph-path');
        var box = element.getBBox();
        var maxScaleVal = 1.4;
        var scaleVal =1;
        var norme = 7.75;

        // find scaleValue
        if ($scope.city.attributes.ph > norme) {
          scaleVal = ((($scope.city.attributes.ph / norme) - 1) * (maxScaleVal - 1)) + 1;
          scaleVal = scaleVal > maxScaleVal ? maxScaleVal : scaleVal;
        } else {
          scaleVal = $scope.city.attributes.ph / norme;
        }

        // reajust data on la goutte
        var cx = 204;
        var cy = 219.5;
        element.setAttribute('transform', 'translate(' + cx + ' ' + cy + ') scale(' + scaleVal + ') translate(' + (-cx) + ' ' + (-cy) + ')');
       // })

        // onmouseenter
        document.getElementById('ammonium-path').onmouseover=function(){changeDescriptionText('explications-ammonium')};
        document.getElementById('chlore-path').onmouseover=function(){changeDescriptionText('explications-chlore')};
        document.getElementById('conductivite-path').onmouseover=function(){changeDescriptionText('explications-conductivite')};
        document.getElementById('nitrates-path').onmouseover=function(){changeDescriptionText('explications-nitrates')};
        document.getElementById('ph-path').onmouseover=function(){changeDescriptionText('explications-ph')};

        // onmouseout
        document.getElementById('ammonium-path').onmouseout=function(){changeDescriptionText('explication-aqualite')};
        document.getElementById('chlore-path').onmouseout=function(){changeDescriptionText('explication-aqualite')};
        document.getElementById('conductivite-path').onmouseout=function(){changeDescriptionText('explication-aqualite')};
        document.getElementById('nitrates-path').onmouseout=function(){changeDescriptionText('explication-aqualite')};
        document.getElementById('ph-path').onmouseout=function(){changeDescriptionText('explication-aqualite')};
      });
    });
  }
}


text:
package kr.co.mapchat.fragments;

import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import kr.co.mapchat.MainActivity;
import kr.co.mapchat.R;

public class FragmentBookmark extends Fragment {
    View view;

    public FragmentBookmark(){ setHasOptionsMenu(true); }

    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_bookmark, null, false);

        getActivity().supportInvalidateOptionsMenu();
        ((MainActivity)getActivity()).changeTitle(R.id.toolbar, "즐겨찾기");

        return view;
    }
}


text:
USER=$(whoami)
HOME=/home/$USER
CODENAME=$(lsb_release -sc)
DOTFILES_ROOT="https://raw.githubusercontent.com/thomasgohard/dotfiles/master/"
INPUTRC=.inputrc
VIMRC=.vimrc
VIRTUALBOX_DEB="deb http://download.virtualbox.org/virtualbox/debian $CODENAME contrib"
VIRTUALBOX_EXTPACK="http://download.virtualbox.org/virtualbox/{version}/Oracle_VM_VirtualBox_Extension_Pack-{version}-{release}.vbox-extpack"

gsettings set org.gnome.settings-daemon.peripherals.touchpad natural-scroll true
gsettings set com.canonical.Unity.Lenses remote-content-search none

if ! grep -Fxq "$VIRTUALBOX_DEB" /etc/apt/sources.list; then
	sudo add-apt-repository "$VIRTUALBOX_DEB"
	wget -q https://www.virtualbox.org/download/oracle_vbox.asc -O- | sudo apt-key add -
fi

sudo apt-get update -y
sudo apt-get install vim git virtualbox-5.0 dkms vagrant inkscape -y

VIRTUALBOX_EXTPACK=${VIRTUALBOX_EXTPACK//\{version\}/$(VBoxManage -v | cut -dr -f 1)}
VIRTUALBOX_EXTPACK=${VIRTUALBOX_EXTPACK//\{release\}/$(VBoxManage -v | cut -dr -f 2)}

wget $VIRTUALBOX_EXTPACK
sudo VBoxManage extpack install --replace ${VIRTUALBOX_EXTPACK##*/} && rm ${VIRTUALBOX_EXTPACK##*/}

if [ -f "$HOME/$INPUTRC" ]; then
	rm "$HOME/$INPUTRC"
fi
wget -O $HOME/$INPUTRC $DOTFILES_ROOT/$INPUTRC

if [ -f "$HOME/$VIMRC" ]; then
	rm "$HOME/$VIMRC"
fi
wget -O $HOME/$VIMRC $DOTFILES_ROOT/$VIMRC

exit 0


text:
public class DecimalToBinary{
	public static void main(String[] arg){

		System.out.println(decimalToBinary(23));
		System.out.println(decimalToBinary(224));

	}

	public static String decimalToBinary(int n){
		String result = ""; // store the result
		int a = n; // don't want to change the initial value n
		for(;a>0; a/=2){ // a/=2 because we will add 1 or 0 on the new quotient
			if(a<2){
				result += "1";
				// if the quotient is less than 2, add 1 and the loop comes to an end because it will fail the for statement a>0 next time around
			} else if(a%2 == 0){
				result += "0";
				// if there is no remainder, add 0 to string result
			} else if(a % 2 != 0){
				result += "1";
				// if there is remainder, add 1 to string result
			}
		}
		while (result.length()<8){
			result += "0";
			// if the result is not yet a 8 digit number, add 0 until it's a 8 digit
		}
		String reverse = "";
		// since i was adding numbers to result from the behind, i need to reverse it to get the correct binary

		for(int i=result.length() -1 ; i>=0; i--){
			reverse+=result.charAt(i);
		}

		return reverse;
	}

}


text:
'use strict';

const gulp    = require('gulp');
const mocha   = require('gulp-mocha');
const eslint  = require('gulp-eslint');
const nodemon = require('gulp-nodemon');

const paths = ['*.js', './lib/*.js', './controller/**/*.js', './routes/*.js', './model/*.js', './test/*.js'];

gulp.task('lint', function(){
  gulp.src(paths)
  .pipe(eslint())
  .pipe(eslint.format())
  .pipe(eslint.failAfterError());
});

gulp.task('test', function(){
  return gulp.src('./test/*-test.js', {read: false})
  .pipe(mocha());
});

gulp.task('nodemon', function(){
  nodemon({
    ext: 'js',
    script: 'server.js'
  });
});

gulp.task('default', ['test', 'lint']);


text:
<!--
  ~ Part of the Codex Project packages.
  ~
  ~ License and copyright information bundled with this package in the LICENSE file.
  ~
  ~ @author Robin Radic
  ~ @copyright Copyright 2016 (c) Codex Project
  ~ @license http://codex-project.ninja/license The MIT License
  -->

<project name="auth-hook" default="pre-commit">

    <property name="buildfile-version" value="1.0.0"/>
    <property name="vendordir" value="${project.basedir}/../../../vendor"/>
    <property name="toolsdir" value=""/>
    <property name="phpdocfile" value="${project.basedir}/docs/structure.xml"/>

    <target name="clean" unless="clean.done" description="Cleanup build artifacts">
        <delete dir="${project.basedir}/vendor"/>
        <delete file="${project.basedir}/composer.lock"/>
        <property name="clean.done" value="true"/>
    </target>

    <target name="pre-commit" unless="pre-commit.done" depends="clean" description="Prepare for build">
        <phingcall target="lint"/>
        <phingcall target="phpcs"/>
        <phingcall target="phpunit"/>
        <phingcall target="phpdoc"/>
        <property name="pre-commit.done" value="true"/>
    </target>

    <target name="lint" description="Perform syntax check of sourcecode files">
        <apply executable="php" failonerror="true">
            <arg value="-l"/>

            <fileset dir="${project.basedir}/src" >
                <include name="**/*.php"/>
            </fileset>

        </apply>
    </target>

    <target name="phpcbf" description="Fixes coding standard violations using PHP_CodeSniffer Fixer">
        <exec executable="${toolsdir}phpcbf" logoutput="true">
            <arg value="--tabWidth=4"/>
            <arg value="--standard=PSR2"/>
            <arg value="--extensions=php"/>
            <arg value="--ignore=autoload.php"/>
            <arg path="${project.basedir}/src"/>
        </exec>
    </target>

    <target name="phpcs" depends="phpcbf" description="Find coding standard violations using PHP_CodeSniffer and print human readable output. Intended for usage on the command line before committing.">
        <exec executable="${toolsdir}phpcs" logoutput="true">
            <arg value="--standard=PSR2"/>
            <arg value="--extensions=php"/>
            <arg value="--ignore=autoload.php"/>
            <arg path="${project.basedir}/src"/>
        </exec>
    </target>

    <target name="phpunit" description="Run unit tests with PHPUnit">
        <exec executable="${toolsdir}phpunit" logoutput="true">
            <arg value="--configuration"/>
            <arg path="${project.basedir}/phpunit.xml"/>
            <arg value="--bootstrap"/>
            <arg path="${vendordir}/autoload.php"/>
        </exec>
    </target>

    <target name="phpdoc" description="Generate phpdoc structure xml and move into docs folder">
        <exec executable="${toolsdir}phpdoc" dir="${project.basedir}" logoutput="true">
            <arg line="-t ./phpdoc"/>
            <arg line="-d ./src"/>
            <arg line="--template=xml"/>
        </exec>
        <move file="${project.basedir}/phpdoc/structure.xml" tofile="${phpdocfile}"/>
        <delete dir="${project.basedir}/phpdoc"/>
    </target>

</project>


text:
sap.ui.define([
	"sap/ui/core/Element"
], function(Element) {

	/**
	 * Helper object used to evaluate expressions.
	 * @class
	 * @name spet.auth.selector.ExpressionHelper
	 * @property	{boolean}	result	The result of the expression.
	 */
	return Element.extend("spet.auth.selector.ExpressionHelper", {
		metadata: {
			properties: {
				result: {type: "boolean", defaultValue: false}
			}
		}
	});

}, /* bExport = */ false);


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>Application</title>
<meta name="date" content="2014-11-12">
<link rel="stylesheet" type="text/css" href="stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

Class Application

java.lang.Object

Application

public class Application
extends java.lang.Object

The Class Application.

Field Summary

Fields

Modifier and Type
Field and Description

protected ApplicationData
applicationData

The data for the application.

private javax.swing.JPanel
Bottom_Left

The Bottom_ left.

private javax.swing.JPanel
Bottom_Right

The Bottom_ right.

(package private) java.text.DecimalFormat
decimalFormat

The decimal format.

private javax.swing.JFrame
frmNpcConversationalAi

The frm npc conversational ai.

private java.awt.Component
horizontalStrut

The horizontal strut.

private java.awt.Component
horizontalStrut_1

The horizontal strut_1.

private javax.swing.JTextField
initiatorBox

The initiator box.

private javax.swing.JLabel
lblConversationInitiator

The lbl conversation initiator.

private javax.swing.JLabel
lblPreviousTopic

The lbl previous topic.

private javax.swing.JLabel
lblResponder

The lbl responder.

private javax.swing.JLabel
lblStatement

The lbl statement.

private javax.swing.JLabel
lblStatement_1

The lbl statement_1.

private javax.swing.JLabel
lblTopicOfConversation

The lbl topic of conversation.

protected Statement
leftStatement

The left statement.

private java.lang.Object
leftStatementObject

The left statement object.

private javax.swing.JMenuItem
mnConversation

The mn conversation.

private javax.swing.JMenu
mntmLoad

The mntm load.

private javax.swing.JMenuItem
mntmPeople

The mntm people.

private javax.swing.JMenuItem
mntmReset

The mntm reset.

private javax.swing.JMenuItem
mntmTopics

The mntm topics.

private javax.swing.JPanel
panel_1

The panel_1.

private javax.swing.JPanel
panel_10

The panel_10.

private javax.swing.JPanel
panel_4

The panel_4.

private javax.swing.JPanel
panel_7

The panel_7.

private javax.swing.JPanel
PersonInfoLeft

The Person info left.

private javax.swing.JPanel
PersonInfoRight

The Person info right.

private javax.swing.JTextField
PersonLeft_A

The Person left_ a.

private javax.swing.JTextField
PersonLeft_Anger

The Person left_ anger.

private javax.swing.JTextField
PersonLeft_Antic

The Person left_ antic.

private javax.swing.JTextField
PersonLeft_C

The Person left_ c.

private javax.swing.JTextField
PersonLeft_Disgust

The Person left_ disgust.

private javax.swing.JTextField
PersonLeft_E

The Person left_ e.

private javax.swing.JTextField
PersonLeft_Fear

The Person left_ fear.

private javax.swing.JTextField
PersonLeft_Joy

The Person left_ joy.

private javax.swing.JTextField
PersonLeft_N

The Person left_ n.

private javax.swing.JTextField
PersonLeft_O

The Person left_ o.

private javax.swing.JTextField
PersonLeft_Sad

The Person left_ sad.

private javax.swing.JTextField
PersonLeft_Surprise

The Person left_ surprise.

private javax.swing.JTextField
PersonLeft_Trust

The Person left_ trust.

private javax.swing.JTextField
PersonRight_A

The Person right_ a.

private javax.swing.JTextField
PersonRight_Anger

The Person right_ anger.

private javax.swing.JTextField
PersonRight_Antic

The Person right_ antic.

private javax.swing.JTextField
PersonRight_C

The Person right_ c.

private javax.swing.JTextField
PersonRight_Disgust

The Person right_ disgust.

private javax.swing.JTextField
PersonRight_E

The Person right_ e.

private javax.swing.JTextField
PersonRight_Fear

The Person right_ fear.

private javax.swing.JTextField
PersonRight_Joy

The Person right_ joy.

private javax.swing.JTextField
PersonRight_N

The Person right_ n.

private javax.swing.JTextField
PersonRight_O

The Person right_ o.

private javax.swing.JTextField
PersonRight_Sad

The Person right_ sad.

private javax.swing.JTextField
PersonRight_Surprise

The Person right_ surprise.

private javax.swing.JTextField
PersonRight_Trust

The Person right_ trust.

private javax.swing.JTextField
previousTopicBox

The place holder.

private javax.swing.JTextField
responderBox

The responder box.

protected Statement
rightStatement

The right statement.

private java.lang.Object
rightStatementObject

The right statement object.

private javax.swing.JButton
sayRight

The btn say left.

private javax.swing.JButton
startConvo

The start convo.

private javax.swing.JPanel
StatementInfoLeft

The Statement info left.

private javax.swing.JPanel
StatementInfoRight

The Statement info right.

private javax.swing.JTextField
StatementLeft_A

The Statement left_ a.

private javax.swing.JTextField
StatementLeft_Anger

The Statement left_ anger.

private javax.swing.JTextField
StatementLeft_Antic

The Statement left_ antic.

private javax.swing.JTextField
StatementLeft_C

The Statement left_ c.

private javax.swing.JTextField
StatementLeft_Disgust

The Statement left_ disgust.

private javax.swing.JTextField
StatementLeft_E

The Statement left_ e.

private javax.swing.JTextField
StatementLeft_Fear

The Statement left_ fear.

private javax.swing.JTextField
StatementLeft_Joy

The Statement left_ joy.

private javax.swing.JTextField
StatementLeft_N

The Statement left_ n.

private javax.swing.JTextField
StatementLeft_O

The Statement left_ o.

private javax.swing.JTextField
StatementLeft_Sadness

The Statement left_ sadness.

private javax.swing.JTextField
StatementLeft_Surprise

The Statement left_ surprise.

private javax.swing.JTextField
StatementLeft_Trust

The Statement left_ trust.

private javax.swing.JTextField
StatementRight_A

The Statement right_ a.

private javax.swing.JTextField
StatementRight_Anger

The Statement right_ anger.

private javax.swing.JTextField
StatementRight_Antic

The Statement right_ antic.

private javax.swing.JTextField
StatementRight_C

The Statement right_ c.

private javax.swing.JTextField
StatementRight_Disgust

The Statement right_ disgust.

private javax.swing.JTextField
StatementRight_E

The Statement right_ e.

private javax.swing.JTextField
StatementRight_Fear

The Statement right_ fear.

private javax.swing.JTextField
StatementRight_Joy

The Statement right_ joy.

private javax.swing.JTextField
StatementRight_N

The Statement right_ n.

private javax.swing.JTextField
StatementRight_O

The Statement right_ o.

private javax.swing.JTextField
StatementRight_Sad

The Statement right_ sad.

private javax.swing.JTextField
StatementRight_Surprise

The Statement right_ surprise.

private javax.swing.JTextField
StatementRight_Trust

The Statement right_ trust.

private javax.swing.JComboBox
StatementSelectLeft

The Statement select left.

private javax.swing.JComboBox
StatementSelectRight

The Statement select right.

private javax.swing.JTextField
textField_101

The text field_101.

private javax.swing.JTextField
textField_102

The text field_102.

private javax.swing.JTextField
textField_19

The text field_19.

private javax.swing.JTextField
textField_2

The text field_2.

private javax.swing.JTextField
textField_20

The text field_20.

private javax.swing.JTextField
textField_21

The text field_21.

private javax.swing.JTextField
textField_22

The text field_22.

private javax.swing.JTextField
textField_24

The text field_24.

private javax.swing.JTextField
textField_25

The text field_25.

private javax.swing.JTextField
textField_27

The text field_27.

private javax.swing.JTextField
textField_28

The text field_28.

private javax.swing.JTextField
textField_29

The text field_29.

private javax.swing.JTextField
textField_3

The text field_3.

private javax.swing.JTextField
textField_30

The text field_30.

private javax.swing.JTextField
textField_4

The text field_4.

private javax.swing.JTextField
textField_44

The text field_44.

private javax.swing.JTextField
textField_45

The text field_45.

private javax.swing.JTextField
textField_46

The text field_46.

private javax.swing.JTextField
textField_47

The text field_47.

private javax.swing.JTextField
textField_49

The text field_49.

private javax.swing.JTextField
textField_5

The text field_5.

private javax.swing.JTextField
textField_50

The text field_50.

private javax.swing.JTextField
textField_53

The text field_53.

private javax.swing.JTextField
textField_54

The text field_54.

private javax.swing.JTextField
textField_55

The text field_55.

private javax.swing.JTextField
textField_56

The text field_56.

private javax.swing.JTextField
textField_70

The text field_70.

private javax.swing.JTextField
textField_71

The text field_71.

private javax.swing.JTextField
textField_72

The text field_72.

private javax.swing.JTextField
textField_73

The text field_73.

private javax.swing.JTextField
textField_75

The text field_75.

private javax.swing.JTextField
textField_76

The text field_76.

private javax.swing.JTextField
textField_79

The text field_79.

private javax.swing.JTextField
textField_80

The text field_80.

private javax.swing.JTextField
textField_81

The text field_81.

private javax.swing.JTextField
textField_82

The text field_82.

private javax.swing.JTextField
textField_96

The text field_96.

private javax.swing.JTextField
textField_97

The text field_97.

private javax.swing.JTextField
textField_98

The text field_98.

private javax.swing.JTextField
textField_99

The text field_99.

private javax.swing.JPanel
Top_Left

The Top_ left.

private javax.swing.JPanel
Top_Right

The Top_ right.

private javax.swing.JTextField
topicOfConversationBox

The Topic of conversation.

private javax.swing.JTextField
txtDisgust

The txt disgust.

private javax.swing.JTextField
txtDisgust_1

The txt disgust_1.

private javax.swing.JTextField
txtDisgust_2

The txt disgust_2.

private javax.swing.JTextField
txtDisgust_3

The txt disgust_3.

private javax.swing.JTextField
txtOpenToExperience

The txt open to experience.

private javax.swing.JTextField
txtOpenToExperience_1

The txt open to experience_1.

private javax.swing.JTextField
txtOpenToExperience_2

The txt open to experience_2.

private javax.swing.JTextField
txtOpenToExperience_3

The txt open to experience_3.

private javax.swing.JTextField
txtTrust

The txt trust.

private javax.swing.JTextField
txtTrust_1

The txt trust_1.

private javax.swing.JTextField
txtTrust_2

The txt trust_2.

private javax.swing.JTextField
txtTrust_3

The txt trust_3.

private java.awt.Component
verticalStrut

The vertical strut.

private java.awt.Component
verticalStrut_1

The vertical strut_1.

Constructor Summary

Constructors

Constructor and Description

Application()

Create the application.

Method Summary

Methods

Modifier and Type
Method and Description

private void
initializeGUI(Application application)

Initialize the contents of the frame.

static void
main(java.lang.String[] args)

Launch the application.

Person
searchPerson(java.lang.String name,
            java.util.LinkedList<Person> people)

Searches the list of people for the person specified.

Statement
searchStatement(Topic topic,
               java.lang.String text)

Searches the given topic for the statement with text specified.

Topic
searchTopic(java.lang.String title,
           java.util.LinkedList<Topic> topics)

Searches the list of topics for the topic specified.

void
updateLeftGUI()

Updates the GUI depending on current variables (selections in boxes).

void
updateRightGUI()

Updates the GUI depending on current variables (selections in boxes).

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

applicationData

protected ApplicationData applicationData

The data for the application.

leftStatement

protected Statement leftStatement

The left statement.

rightStatement

protected Statement rightStatement

The right statement.

rightStatementObject

private java.lang.Object rightStatementObject

The right statement object.

leftStatementObject

private java.lang.Object leftStatementObject

The left statement object.

responderBox

private javax.swing.JTextField responderBox

The responder box.

initiatorBox

private javax.swing.JTextField initiatorBox

The initiator box.

decimalFormat

java.text.DecimalFormat decimalFormat

The decimal format.

frmNpcConversationalAi

private javax.swing.JFrame frmNpcConversationalAi

The frm npc conversational ai.

Bottom_Right

private javax.swing.JPanel Bottom_Right

The Bottom_ right.

Top_Right

private javax.swing.JPanel Top_Right

The Top_ right.

PersonInfoRight

private javax.swing.JPanel PersonInfoRight

The Person info right.

txtOpenToExperience_2

private javax.swing.JTextField txtOpenToExperience_2

The txt open to experience_2.

textField_27

private javax.swing.JTextField textField_27

The text field_27.

textField_28

private javax.swing.JTextField textField_28

The text field_28.

textField_29

private javax.swing.JTextField textField_29

The text field_29.

textField_30

private javax.swing.JTextField textField_30

The text field_30.

PersonRight_O

private javax.swing.JTextField PersonRight_O

The Person right_ o.

PersonRight_C

private javax.swing.JTextField PersonRight_C

The Person right_ c.

PersonRight_E

private javax.swing.JTextField PersonRight_E

The Person right_ e.

PersonRight_A

private javax.swing.JTextField PersonRight_A

The Person right_ a.

PersonRight_N

private javax.swing.JTextField PersonRight_N

The Person right_ n.

PersonRight_Joy

private javax.swing.JTextField PersonRight_Joy

The Person right_ joy.

PersonRight_Sad

private javax.swing.JTextField PersonRight_Sad

The Person right_ sad.

PersonRight_Anger

private javax.swing.JTextField PersonRight_Anger

The Person right_ anger.

PersonRight_Fear

private javax.swing.JTextField PersonRight_Fear

The Person right_ fear.

PersonRight_Trust

private javax.swing.JTextField PersonRight_Trust

The Person right_ trust.

PersonRight_Surprise

private javax.swing.JTextField PersonRight_Surprise

The Person right_ surprise.

PersonRight_Antic

private javax.swing.JTextField PersonRight_Antic

The Person right_ antic.

PersonRight_Disgust

private javax.swing.JTextField PersonRight_Disgust

The Person right_ disgust.

textField_44

private javax.swing.JTextField textField_44

The text field_44.

textField_45

private javax.swing.JTextField textField_45

The text field_45.

textField_46

private javax.swing.JTextField textField_46

The text field_46.

textField_47

private javax.swing.JTextField textField_47

The text field_47.

txtTrust_2

private javax.swing.JTextField txtTrust_2

The txt trust_2.

textField_49

private javax.swing.JTextField textField_49

The text field_49.

textField_50

private javax.swing.JTextField textField_50

The text field_50.

txtDisgust_2

private javax.swing.JTextField txtDisgust_2

The txt disgust_2.

Bottom_Left

private javax.swing.JPanel Bottom_Left

The Bottom_ left.

Top_Left

private javax.swing.JPanel Top_Left

The Top_ left.

StatementInfoRight

private javax.swing.JPanel StatementInfoRight

The Statement info right.

txtOpenToExperience_3

private javax.swing.JTextField txtOpenToExperience_3

The txt open to experience_3.

textField_2

private javax.swing.JTextField textField_2

The text field_2.

textField_3

private javax.swing.JTextField textField_3

The text field_3.

textField_4

private javax.swing.JTextField textField_4

The text field_4.

textField_5

private javax.swing.JTextField textField_5

The text field_5.

StatementRight_O

private javax.swing.JTextField StatementRight_O

The Statement right_ o.

StatementRight_C

private javax.swing.JTextField StatementRight_C

The Statement right_ c.

StatementRight_E

private javax.swing.JTextField StatementRight_E

The Statement right_ e.

StatementRight_A

private javax.swing.JTextField StatementRight_A

The Statement right_ a.

StatementRight_N

private javax.swing.JTextField StatementRight_N

The Statement right_ n.

panel_1

private javax.swing.JPanel panel_1

The panel_1.

StatementRight_Joy

private javax.swing.JTextField StatementRight_Joy

The Statement right_ joy.

StatementRight_Sad

private javax.swing.JTextField StatementRight_Sad

The Statement right_ sad.

StatementRight_Anger

private javax.swing.JTextField StatementRight_Anger

The Statement right_ anger.

StatementRight_Fear

private javax.swing.JTextField StatementRight_Fear

The Statement right_ fear.

StatementRight_Trust

private javax.swing.JTextField StatementRight_Trust

The Statement right_ trust.

StatementRight_Surprise

private javax.swing.JTextField StatementRight_Surprise

The Statement right_ surprise.

StatementRight_Antic

private javax.swing.JTextField StatementRight_Antic

The Statement right_ antic.

StatementRight_Disgust

private javax.swing.JTextField StatementRight_Disgust

The Statement right_ disgust.

textField_19

private javax.swing.JTextField textField_19

The text field_19.

textField_20

private javax.swing.JTextField textField_20

The text field_20.

textField_21

private javax.swing.JTextField textField_21

The text field_21.

textField_22

private javax.swing.JTextField textField_22

The text field_22.

txtTrust_3

private javax.swing.JTextField txtTrust_3

The txt trust_3.

textField_24

private javax.swing.JTextField textField_24

The text field_24.

textField_25

private javax.swing.JTextField textField_25

The text field_25.

txtDisgust_3

private javax.swing.JTextField txtDisgust_3

The txt disgust_3.

PersonInfoLeft

private javax.swing.JPanel PersonInfoLeft

The Person info left.

txtOpenToExperience

private javax.swing.JTextField txtOpenToExperience

The txt open to experience.

textField_53

private javax.swing.JTextField textField_53

The text field_53.

textField_54

private javax.swing.JTextField textField_54

The text field_54.

textField_55

private javax.swing.JTextField textField_55

The text field_55.

textField_56

private javax.swing.JTextField textField_56

The text field_56.

PersonLeft_O

private javax.swing.JTextField PersonLeft_O

The Person left_ o.

PersonLeft_C

private javax.swing.JTextField PersonLeft_C

The Person left_ c.

PersonLeft_E

private javax.swing.JTextField PersonLeft_E

The Person left_ e.

PersonLeft_A

private javax.swing.JTextField PersonLeft_A

The Person left_ a.

PersonLeft_N

private javax.swing.JTextField PersonLeft_N

The Person left_ n.

panel_4

private javax.swing.JPanel panel_4

The panel_4.

PersonLeft_Joy

private javax.swing.JTextField PersonLeft_Joy

The Person left_ joy.

PersonLeft_Sad

private javax.swing.JTextField PersonLeft_Sad

The Person left_ sad.

PersonLeft_Anger

private javax.swing.JTextField PersonLeft_Anger

The Person left_ anger.

PersonLeft_Fear

private javax.swing.JTextField PersonLeft_Fear

The Person left_ fear.

PersonLeft_Trust

private javax.swing.JTextField PersonLeft_Trust

The Person left_ trust.

PersonLeft_Surprise

private javax.swing.JTextField PersonLeft_Surprise

The Person left_ surprise.

PersonLeft_Antic

private javax.swing.JTextField PersonLeft_Antic

The Person left_ antic.

PersonLeft_Disgust

private javax.swing.JTextField PersonLeft_Disgust

The Person left_ disgust.

textField_70

private javax.swing.JTextField textField_70

The text field_70.

textField_71

private javax.swing.JTextField textField_71

The text field_71.

textField_72

private javax.swing.JTextField textField_72

The text field_72.

textField_73

private javax.swing.JTextField textField_73

The text field_73.

txtTrust

private javax.swing.JTextField txtTrust

The txt trust.

textField_75

private javax.swing.JTextField textField_75

The text field_75.

textField_76

private javax.swing.JTextField textField_76

The text field_76.

txtDisgust

private javax.swing.JTextField txtDisgust

The txt disgust.

StatementInfoLeft

private javax.swing.JPanel StatementInfoLeft

The Statement info left.

txtOpenToExperience_1

private javax.swing.JTextField txtOpenToExperience_1

The txt open to experience_1.

textField_79

private javax.swing.JTextField textField_79

The text field_79.

textField_80

private javax.swing.JTextField textField_80

The text field_80.

textField_81

private javax.swing.JTextField textField_81

The text field_81.

textField_82

private javax.swing.JTextField textField_82

The text field_82.

StatementLeft_O

private javax.swing.JTextField StatementLeft_O

The Statement left_ o.

StatementLeft_C

private javax.swing.JTextField StatementLeft_C

The Statement left_ c.

StatementLeft_E

private javax.swing.JTextField StatementLeft_E

The Statement left_ e.

StatementLeft_A

private javax.swing.JTextField StatementLeft_A

The Statement left_ a.

StatementLeft_N

private javax.swing.JTextField StatementLeft_N

The Statement left_ n.

panel_10

private javax.swing.JPanel panel_10

The panel_10.

StatementLeft_Joy

private javax.swing.JTextField StatementLeft_Joy

The Statement left_ joy.

StatementLeft_Sadness

private javax.swing.JTextField StatementLeft_Sadness

The Statement left_ sadness.

StatementLeft_Anger

private javax.swing.JTextField StatementLeft_Anger

The Statement left_ anger.

StatementLeft_Fear

private javax.swing.JTextField StatementLeft_Fear

The Statement left_ fear.

StatementLeft_Trust

private javax.swing.JTextField StatementLeft_Trust

The Statement left_ trust.

StatementLeft_Surprise

private javax.swing.JTextField StatementLeft_Surprise

The Statement left_ surprise.

StatementLeft_Antic

private javax.swing.JTextField StatementLeft_Antic

The Statement left_ antic.

StatementLeft_Disgust

private javax.swing.JTextField StatementLeft_Disgust

The Statement left_ disgust.

textField_96

private javax.swing.JTextField textField_96

The text field_96.

textField_97

private javax.swing.JTextField textField_97

The text field_97.

textField_98

private javax.swing.JTextField textField_98

The text field_98.

textField_99

private javax.swing.JTextField textField_99

The text field_99.

txtTrust_1

private javax.swing.JTextField txtTrust_1

The txt trust_1.

textField_101

private javax.swing.JTextField textField_101

The text field_101.

textField_102

private javax.swing.JTextField textField_102

The text field_102.

txtDisgust_1

private javax.swing.JTextField txtDisgust_1

The txt disgust_1.

StatementSelectLeft

private javax.swing.JComboBox StatementSelectLeft

The Statement select left.

StatementSelectRight

private javax.swing.JComboBox StatementSelectRight

The Statement select right.

verticalStrut

private java.awt.Component verticalStrut

The vertical strut.

verticalStrut_1

private java.awt.Component verticalStrut_1

The vertical strut_1.

topicOfConversationBox

private javax.swing.JTextField topicOfConversationBox

The Topic of conversation.

previousTopicBox

private javax.swing.JTextField previousTopicBox

The place holder.

sayRight

private javax.swing.JButton sayRight

The btn say left.

lblTopicOfConversation

private javax.swing.JLabel lblTopicOfConversation

The lbl topic of conversation.

lblStatement

private javax.swing.JLabel lblStatement

The lbl statement.

lblStatement_1

private javax.swing.JLabel lblStatement_1

The lbl statement_1.

lblPreviousTopic

private javax.swing.JLabel lblPreviousTopic

The lbl previous topic.

panel_7

private javax.swing.JPanel panel_7

The panel_7.

lblConversationInitiator

private javax.swing.JLabel lblConversationInitiator

The lbl conversation initiator.

horizontalStrut

private java.awt.Component horizontalStrut

The horizontal strut.

lblResponder

private javax.swing.JLabel lblResponder

The lbl responder.

horizontalStrut_1

private java.awt.Component horizontalStrut_1

The horizontal strut_1.

startConvo

private javax.swing.JButton startConvo

The start convo.

mntmReset

private javax.swing.JMenuItem mntmReset

The mntm reset.

mnConversation

private javax.swing.JMenuItem mnConversation

The mn conversation.

mntmLoad

private javax.swing.JMenu mntmLoad

The mntm load.

mntmTopics

private javax.swing.JMenuItem mntmTopics

The mntm topics.

mntmPeople

private javax.swing.JMenuItem mntmPeople

The mntm people.

Constructor Detail

Application

public Application()

Create the application.

Method Detail

main

public static void main(java.lang.String[] args)

Launch the application.

Parameters:

args - the arguments

searchStatement

public Statement searchStatement(Topic topic,
                        java.lang.String text)

Searches the given topic for the statement with text specified.

Parameters:

topic - the topic

text - The text of the statement to search for

Returns:

the statement with the same text as the input

updateLeftGUI

public void updateLeftGUI()

Updates the GUI depending on current variables (selections in boxes).

updateRightGUI

public void updateRightGUI()

Updates the GUI depending on current variables (selections in boxes).

initializeGUI

private void initializeGUI(Application application)

Initialize the contents of the frame.

Parameters:

application - the application

searchPerson

public Person searchPerson(java.lang.String name,
                  java.util.LinkedList<Person> people)

Searches the list of people for the person specified.

Parameters:

name - The name of the person to search for

people - the people

Returns:

the person with the same name as the input

searchTopic

public Topic searchTopic(java.lang.String title,
                java.util.LinkedList<Topic> topics)

Searches the list of topics for the topic specified.

Parameters:

title - the title

topics - the topics

Returns:

the topic with the same title as the input

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


text:
"""Run Performance Test Bisect Tool

This script is used by a trybot to run the src/tools/bisect-perf-regression.py
script with the parameters specified in run-bisect-perf-regression.cfg. It will
check out a copy of the depot in a subdirectory 'bisect' of the working
directory provided, and run the bisect-perf-regression.py script there.

"""

import imp
import optparse
import os
import subprocess
import sys

def LoadConfigFile(path_to_file):
  """Attempts to load the file 'run-bisect-perf-regression.cfg' as a module
  and grab the global config dict.

  Args:
    path_to_file: Path to the run-bisect-perf-regression.cfg file.

  Returns:
    The config dict which should be formatted as follows:
    {'command': string, 'good_revision': string, 'bad_revision': string
     'metric': string}.
    Returns None on failure.
  """
  try:
    local_vars = {}
    execfile(os.path.join(path_to_file, 'run-bisect-perf-regression.cfg'),
             local_vars)

    return local_vars['config']
  except:
    return None

def RunBisectionScript(config, working_directory, path_to_file, path_to_goma):
  """Attempts to execute src/tools/bisect-perf-regression.py with the parameters
  passed in.

  Args:
    config: A dict containing the parameters to pass to the script.
    working_directory: A working directory to provide to the
      bisect-perf-regression.py script, where it will store it's own copy of
      the depot.
    path_to_file: Path to the bisect-perf-regression.py script.
    path_to_goma: Path to goma directory.

  Returns:
    0 on success, otherwise 1.
  """

  cmd = ['python', os.path.join(path_to_file, 'bisect-perf-regression.py'),
         '-c', config['command'],
         '-g', config['good_revision'],
         '-b', config['bad_revision'],
         '-m', config['metric'],
         '--working_directory', working_directory,
         '--output_buildbot_annotations']

  if config['repeat_count']:
    cmd.extend(['-r', config['repeat_count']])

  if config['truncate_percent']:
    cmd.extend(['-t', config['truncate_percent']])

  if config['max_time_minutes']:
    cmd.extend(['--repeat_test_max_time', config['max_time_minutes']])

  if os.name == 'nt':
    cmd.extend(['--build_preference', 'ninja'])
  else:
    cmd.extend(['--build_preference', 'make'])

  goma_file = ''
  if path_to_goma:
    path_to_goma = os.path.abspath(path_to_goma)

    if os.name == 'nt':
      os.environ['CC'] = os.path.join(path_to_goma, 'gomacc.exe') + ' cl.exe'
      os.environ['CXX'] = os.path.join(path_to_goma, 'gomacc.exe') + ' cl.exe'
      goma_file = os.path.join(path_to_goma, 'goma_ctl.bat')
    else:
      os.environ['PATH'] = os.pathsep.join([path_to_goma, os.environ['PATH']])
      goma_file = os.path.join(path_to_goma, 'goma_ctl.sh')

    cmd.append('--use_goma')

    # Sometimes goma is lingering around if something went bad on a previous
    # run. Stop it before starting a new process. Can ignore the return code
    # since it will return an error if it wasn't running.
    subprocess.call([goma_file, 'stop'])

    return_code = subprocess.call([goma_file, 'start'])
    if return_code:
      print 'Error: goma failed to start.'
      print
      return return_code

  cmd = [str(c) for c in cmd]

  return_code = subprocess.call(cmd)

  if path_to_goma:
    subprocess.call([goma_file, 'stop'])

  if return_code:
    print 'Error: bisect-perf-regression.py returned with error %d' %\
        return_code
    print

  return return_code

def main():

  usage = ('%prog [options] [-- chromium-options]\n'
           'Used by a trybot to run the bisection script using the parameters'
           ' provided in the run-bisect-perf-regression.cfg file.')

  parser = optparse.OptionParser(usage=usage)
  parser.add_option('-w', '--working_directory',
                    type='str',
                    help='A working directory to supply to the bisection '
                    'script, which will use it as the location to checkout '
                    'a copy of the chromium depot.')
  parser.add_option('-p', '--path_to_goma',
                    type='str',
                    help='Path to goma directory. If this is supplied, goma '
                    'builds will be enabled.')
  (opts, args) = parser.parse_args()

  if not opts.working_directory:
    print 'Error: missing required parameter: --working_directory'
    print
    parser.print_help()
    return 1

  path_to_file = os.path.abspath(os.path.dirname(sys.argv[0]))

  config = LoadConfigFile(path_to_file)
  if not config:
    print 'Error: Could not load config file.'
    print
    return 1

  return RunBisectionScript(config, opts.working_directory, path_to_file,
                            opts.path_to_goma)

if __name__ == '__main__':
  sys.exit(main())


text:
[![Build Status](https://travis-ci.org/Nordeus/pushkin.svg?branch=master)](https://travis-ci.org/Nordeus/pushkin)

## Introduction

Pushkin is a **free open source tool** for sending push notifications. It was developed with a focus on speed and enabling fast experimentation.
Pushkin was mainly built for supporting online mobile games, but can easily be extended to any type of application. It supports both Android and iOS platforms.

Pushkin is designed to be a responsive tool. You can design your systems around Pushkin so it reacts to your game server, database server, client or really any service that can send a HTTP POST request. It is also easily scalable, because you can run as many Pushkin instances as you want. One instance is capable of pushing 500 messages per second.

Pushkin has the MIT license.

---

## Use cases

To fit all use cases, Pushkin has 2 modes of operations:

1. **Push Notification mode** - You can issue a direct notification, meaning that you supply the user and the message. Pushkin will find the device id for the user and send the message. This is the simplest use case.

2. **Event mode** - You can send Pushkin an event, notifying it that something happened to a certain user. Pushkin will then decide whether it can send a notification based on that event or not. If yes, Pushkin will construct the message in the proper language for the user (localization is supported), find the device id of the user mobile device and send the notification.

These two use cases can be seen on the diagram below:

![highlevel](docs/img/Pushkin_Highlevel.png)

---

Read the documentation at [pushkin.io](http://docs.pushkin.io).