text:
#import "AMapMarker.h"

#import "RCTEventDispatcher.h"
#import "UIView+React.h"
#import "RCTBridge.h"
#import "RCTUtils.h"
#import "RCTImageLoader.h"

@implementation EmptyCalloutBackgroundView
@end

@implementation AMapMarker {
    BOOL _hasSetCalloutOffset;
    RCTImageLoaderCancellationBlock _reloadImageCancellationBlock;
    MAPinAnnotationView *_pinView;
}

- (void)reactSetFrame:(CGRect)frame
{
    CGRect bounds = {CGPointZero, frame.size};

    // The MapView is basically in charge of figuring out the center position of the marker view. If the view changed in
    // height though, we need to compensate in such a way that the bottom of the marker stays at the same spot on the
    // map.
    CGFloat dy = (bounds.size.height - self.bounds.size.height) / 2;
    CGPoint center = (CGPoint){ self.center.x, self.center.y - dy };

    // Avoid crashes due to nan coords
    if (isnan(center.x) || isnan(center.y) ||
            isnan(bounds.origin.x) || isnan(bounds.origin.y) ||
            isnan(bounds.size.width) || isnan(bounds.size.height)) {
        RCTLogError(@"Invalid layout for (%@)%@. position: %@. bounds: %@",
                self.reactTag, self, NSStringFromCGPoint(center), NSStringFromCGRect(bounds));
        return;
    }

    self.center = center;
    self.bounds = bounds;
}

- (void)insertReactSubview:(id<RCTComponent>)subview atIndex:(NSInteger)atIndex {
    if ([subview isKindOfClass:[AMapCallout class]]) {
        self.calloutView = (AMapCallout *)subview;
    } else {
        [super insertReactSubview:subview atIndex:atIndex];
    }
}

- (void)removeReactSubview:(id<RCTComponent>)subview {
    if ([subview isKindOfClass:[AMapCallout class]] && self.calloutView == subview) {
        self.calloutView = nil;
    } else {
        [super removeReactSubview:subview];
    }
}

- (MAAnnotationView *)getAnnotationView
{
    if ([self shouldUsePinView]) {
        // In this case, we want to render a platform "default" marker.
        if (_pinView == nil) {
            _pinView = [[MAPinAnnotationView alloc] initWithAnnotation:self reuseIdentifier: nil];
            _pinView.annotation = self;
        }

        _pinView.draggable = self.draggable;

        // TODO(lmr): Looks like this API was introduces in iOS 8. We may want to handle differently for earlier
        // versions. Right now it's just leaving it with the default color. People needing the colors are free to
        // use their own custom markers.

        [_pinView setPinColor:self.pinColor];

        return _pinView;
    } else {
        // If it has subviews, it means we are wanting to render a custom marker with arbitrary react views.
        // if it has a non-null image, it means we want to render a custom marker with the image.
        // In either case, we want to return the AMapMarker since it is both an MAAnnotation and an
        // MAAnnotationView all at the same time.
        return self;
    }
}

- (void)fillCalloutView:(SMCalloutView *)calloutView
{
    // Set everything necessary on the calloutView before it becomes visible.

    // Apply the MAAnnotationView's desired calloutOffset (from the top-middle of the view)
    if ([self shouldUsePinView] && !_hasSetCalloutOffset) {
        calloutView.calloutOffset = CGPointMake(-8,0);
    } else {
        calloutView.calloutOffset = self.calloutOffset;
    }

    if (self.calloutView) {
        calloutView.title = nil;
        calloutView.subtitle = nil;
        if (self.calloutView.tooltip) {
            // if tooltip is true, then the user wants their react view to be the "tooltip" as wwell, so we set
            // the background view to something empty/transparent
            calloutView.backgroundView = [EmptyCalloutBackgroundView new];
        } else {
            // the default tooltip look is wanted, and the user is just filling the content with their react subviews.
            // as a result, we use the default "masked" background view.
            calloutView.backgroundView = [SMCalloutMaskedBackgroundView new];
        }

        // when this is set, the callout's content will be whatever react views the user has put as the callout's
        // children.
        calloutView.contentView = self.calloutView;

    } else {

        // if there is no calloutView, it means the user wants to use the default callout behavior with title/subtitle
        // pairs.
        calloutView.title = self.title;
        calloutView.subtitle = self.subtitle;
        calloutView.contentView = nil;
        calloutView.backgroundView = [SMCalloutMaskedBackgroundView new];
    }
}

- (void)showCalloutView
{
    MAAnnotationView *annotationView = [self getAnnotationView];

    [self setSelected:YES animated:NO];

    id event = @{
            @"action": @"marker-select",
            @"id": self.identifier ?: @"unknown",
            @"coordinate": @{
                    @"latitude": @(self.coordinate.latitude),
                    @"longitude": @(self.coordinate.longitude)
            }
    };

    if (self.map.onMarkerSelect) self.map.onMarkerSelect(event);
    if (self.onSelect) self.onSelect(event);

    if (![self shouldShowCalloutView]) {
        // no callout to show
        return;
    }

    [self fillCalloutView:self.map.calloutView];

    // This is where we present our custom callout view... MapKit's built-in callout doesn't have the flexibility
    // we need, but a lot of work was done by Nick Farina to make this identical to MapKit's built-in.
    [self.map.calloutView presentCalloutFromRect:annotationView.bounds
                                         inView:annotationView
                              constrainedToView:self.map
                                       animated:YES];
}

- (void)hideCalloutView
{
    // hide the callout view
    [self.map.calloutView dismissCalloutAnimated:YES];

    [self setSelected:NO animated:NO];

    id event = @{
            @"action": @"marker-deselect",
            @"id": self.identifier ?: @"unknown",
            @"coordinate": @{
                    @"latitude": @(self.coordinate.latitude),
                    @"longitude": @(self.coordinate.longitude)
            }
    };

    if (self.map.onMarkerDeselect) self.map.onMarkerDeselect(event);
    if (self.onDeselect) self.onDeselect(event);
}

- (void)setCalloutOffset:(CGPoint)calloutOffset
{
    _hasSetCalloutOffset = YES;
    [super setCalloutOffset:calloutOffset];
}

- (BOOL)shouldShowCalloutView
{
    return self.calloutView != nil || self.title != nil || self.subtitle != nil;
}

- (BOOL)shouldUsePinView
{
    return self.subviews.count == 0 && !self.imageSrc;
}

- (void)setImageSrc:(NSString *)imageSrc
{
    _imageSrc = imageSrc;

    if (_reloadImageCancellationBlock) {
        _reloadImageCancellationBlock();
        _reloadImageCancellationBlock = nil;
    }
    _reloadImageCancellationBlock = [_bridge.imageLoader loadImageWithURLRequest:[RCTConvert NSURLRequest:_imageSrc]
                                                                            size:self.bounds.size
                                                                           scale:RCTScreenScale()
                                                                         clipped:YES
                                                                      resizeMode:UIViewContentModeCenter
                                                                   progressBlock:nil
                                                                 completionBlock:^(NSError *error, UIImage *image) {
                                                                     if (error) {
                                                                         // TODO(lmr): do something with the error?
                                                                         NSLog(@"%@", error);
                                                                     }
                                                                     dispatch_async(dispatch_get_main_queue(), ^{
                                                                         self.image = image;
                                                                     });
                                                                 }];
}

- (void)setPinColor:(MAPinAnnotationColor)pinColor
{
    _pinColor = pinColor;
    [_pinView setPinColor:pinColor];
}

@end


text:
<?xml version="1.0" encoding="UTF-8"?>
<archetype-descriptor xsi:schemaLocation="http://maven.apache.org/plugins/maven-archetype-plugin/archetype-descriptor/1.0.0 http://maven.apache.org/xsd/archetype-descriptor-1.0.0.xsd" name="java-kata-archetype"
    xmlns="http://maven.apache.org/plugins/maven-archetype-plugin/archetype-descriptor/1.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <fileSets>
    <fileSet filtered="true" packaged="true" encoding="UTF-8">
      <directory>src/main/java</directory>
      <includes>
        <include>**/*.java</include>
      </includes>
    </fileSet>
    <fileSet filtered="true" packaged="false" encoding="UTF-8">
      <directory>src/main/resources</directory>
      <includes>
        <include>**/*</include>
      </includes>
    </fileSet>
    <fileSet filtered="true" packaged="true" encoding="UTF-8">
      <directory>src/test/java</directory>
      <includes>
        <include>**/*.java</include>
      </includes>
    </fileSet>
    <fileSet filtered="true" packaged="false" encoding="UTF-8">
      <directory>src/test/resources</directory>
      <includes>
        <include>**/*</include>
      </includes>
    </fileSet>
    <fileSet filtered="true" packaged="false" encoding="UTF-8">
      <directory></directory>
      <includes>
        <include>.gitignore</include>
      </includes>
    </fileSet>
  </fileSets>
</archetype-descriptor>

redpajama_set_name: RedPajamaGithub


text:
using Esri.ArcGISRuntime.Layers;
using System;
using System.Diagnostics;
using System.Net.Http;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
using Windows.System;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;

namespace ArcGISRuntimeSDKDotNet_PhoneSamples.Samples.TiledLayers
{
	/// <summary>
	/// This sample demonstrates adding a Bing Maps layer to a Map in code.
	/// A Bing Maps key must be provided to view Bing Maps tiled map services.
	/// </summary>
	/// <title>Bing Maps Layer</title>
	/// <category>Tiled Layers</category>
	public sealed partial class BingLayerSample : Page
	{
		public BingLayerSample()
		{
			InitializeComponent();
		}

		private void RadioButton_Click(object sender, RoutedEventArgs e)
		{
			string layerNameTag = (string)((RadioButton)sender).Tag;

			foreach (Layer layer in MyMap.Layers)
				if (layer is BingLayer)
					layer.IsVisible = false;

			MyMap.Layers[layerNameTag].IsVisible = true;
		}

		private void BingKeyTextBox_TextChanged(object sender, TextChangedEventArgs e)
		{
			if ((sender as TextBox).Text.Length >= 64)
				LoadMapButton.IsEnabled = true;
			else
				LoadMapButton.IsEnabled = false;
		}

		private async void LoadMapButton_Click(object sender, RoutedEventArgs e)
		{
			try
			{
				string uri = string.Format("http://dev.virtualearth.net/REST/v1/Imagery/Metadata/Aerial?supressStatus=true&key={0}", BingKeyTextBox.Text);

				HttpClient http = new System.Net.Http.HttpClient();
				HttpResponseMessage response = await http.GetAsync(uri);
				var bingAuthStream = await response.Content.ReadAsStreamAsync();

				DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(BingAuthentication));
				BingAuthentication bingAuthentication = serializer.ReadObject(bingAuthStream) as BingAuthentication;
				string authenticationResult = bingAuthentication.AuthenticationResultCode.ToString();
				if (authenticationResult == "ValidCredentials")
				{
					foreach (BingLayer.LayerType layerType in (BingLayer.LayerType[])Enum.GetValues(typeof(BingLayer.LayerType)))
					{
						BingLayer bingLayer = new BingLayer()
						{
							ID = layerType.ToString(),
							MapStyle = layerType,
							Key = BingKeyTextBox.Text,
							IsVisible = false
						};

						MyMap.Layers.Add(bingLayer);
					}

					MyMap.Layers[0].IsVisible = true;

					InvalidBingKeyTextBlock.Visibility = Visibility.Collapsed;
					LayerStyleGrid.Visibility = Visibility.Visible;
					InfoText.Visibility = Visibility.Collapsed;
				}
				else
					InvalidBingKeyTextBlock.Visibility = Visibility.Visible;
			}
			catch (Exception ex)
			{
				Debug.WriteLine(ex.ToString());
				InvalidBingKeyTextBlock.Visibility = Visibility.Visible;
			}
		}

		private async void Button_Click(object sender, RoutedEventArgs e)
		{
			await Launcher.LaunchUriAsync(new Uri("https://www.bingmapsportal.com"));
		}

		[DataContract]
		public class BingAuthentication
		{
			[DataMember(Name = "authenticationResultCode")]
			public string AuthenticationResultCode { get; set; }
		}
	}
}


text:
[![Gem Version](https://badge.fury.io/rb/objectifier.svg)](https://badge.fury.io/rb/objectifier)
[![Build Status](https://travis-ci.org/wiggly/objectifier.svg?branch=master)](https://travis-ci.org/wiggly/objectifier)

De-serialise plain hashes into objects.

The rationale behind this is to be able to take input from external sources such as REST calls or log files and turn them into graphs of objects or find out why they cannot be tranformed.

This is the first cut of the code and it currently only handles a small number of types but you can add your own already. Better default types will be coming soon.

## Installation

Add this line to your application's Gemfile:

```ruby
gem 'objectifier'
```

And then execute:

    $ bundle

Or install it yourself as:

    $ gem install objectifier

## Usage

Create custom transformers, create an objectifier and use it to de-serialise hashes.

```
  require 'objectifier'
  require 'money'

  # Add a custom tranformer for Money values
  Objectifier.factories.add_type(
    :money,
    ->(name, value) {
      Objectifier::ValueResult.new(name, Money.new(value["amount"], value["code"]))
    })

  # define an objectifier that can be used to de-serialise a given format
  obj = Objectifier.define do
    item :name, type: :string, required: false

    items :accounts, type: :integer

    item :budget, type: :money

    item :length, type: :integer, required: false

    map :activity do
      item :clicks, type: :integer
      item :ctr, type: :float
    end
  end

  # some test parameters
  parameters = {
    "name" => "Billy",

    "accounts" => [ "100", "300", "150", "23" ],

    "budget" => {
      "amount" => "10.00.0",
      "code" => "GBP",
    },

    "length" => "42",

    "activity" => {
      "clicks" => "83351",
      "ctr" => "3.1",
    },
  }

  # transform input into real objects or return detailed error messages
  result = obj.call(parameters)

  if result.success?
    puts result.value
  else
    puts result
  end
```

## Development

After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake spec` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment.

To install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release`, which will create a git tag for the version, push git commits and tags, and push the `.gem` file to [rubygems.org](https://rubygems.org).

## Contributing

Bug reports and pull requests are welcome on GitHub at https://github.com/wiggly/objectifier.

## License

The gem is available as open source under the terms of the [MIT License](http://opensource.org/licenses/MIT).


text:
require 'spec_helper'

describe 'Base Table Builder' do
	include GrappleSpecHelper

	before do
		@output_buffer = ''
		mock_everything
	end

	it "should be correct" do
		builder = Grapple::DataGridBuilder.new(self, users_columns, users_records, {})

		html = builder.search_submit
		expect(html).to have_tag('input', with: { type: "submit"})

		html = builder.search_query_field
		expect(html).to have_tag('input', with: { type: "text"})

		html = builder.search_form
		expect(html).to have_tag('form')

		html = builder.actions
		expect(html).to have_tag('div.actions')

		html = builder.toolbar
		expect(html).to have_tag('tr.toolbar')

		html = builder.column_headings
		expect(html).to have_tag('tr.column-headers')

	end

end


text: DROP TABLE friendships;


text:
package net.venaglia.nondairy.spellchecker;

import com.intellij.spellchecker.inspections.SpellCheckingInspection;
import com.intellij.testFramework.fixtures.JavaCodeInsightFixtureTestCase;
import net.venaglia.nondairy.SoyTestUtil;
import org.jetbrains.annotations.NonNls;

import java.io.IOException;
import java.net.URLDecoder;

/**
 * @author cpeisert{at}gmail{dot}com (Christopher Peisert)
 */
public abstract class SoySpellcheckerInspectionTestCase
    extends JavaCodeInsightFixtureTestCase {

  protected String getTestDataPath() {
    try {
      return URLDecoder.decode(SoyTestUtil.class.getResource(
          "testSources/spellchecker").getPath(), "UTF-8");
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
  }

  protected void doTest(@NonNls String file) {
    myFixture.enableInspections(new SpellCheckingInspection());
    myFixture.testHighlighting(false, false, true, file);
  }
}


text:
package org.snaker.engine.impl;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.snaker.engine.SnakerInterceptor;
import org.snaker.engine.core.Execution;
import org.snaker.engine.entity.Task;

/**
 * 日志拦截器
 * @author yuqs
 * @version 1.0
 */
public class LogInterceptor implements SnakerInterceptor {
	private static final Logger log = LoggerFactory.getLogger(LogInterceptor.class);
	/**
	 * 拦截产生的任务对象,打印日志
	 */
	public void intercept(Execution execution) {
		if(log.isInfoEnabled()) {
			for(Task task : execution.getTasks()) {
				StringBuffer buffer = new StringBuffer(100);
				buffer.append("创建任务[标识=").append(task.getId());
				buffer.append(",名称=").append(task.getDisplayName());
				buffer.append(",创建时间=").append(task.getCreateTime());
				buffer.append(",参与者={");
				if(task.getActorIds() != null) {
					for(String actor : task.getActorIds()) {
						buffer.append(actor).append(";");
					}
				}
				buffer.append("}]");
				log.info(buffer.toString());
			}
		}
	}
}


text:
@interface NSJSONSerialization (OEXSafeAccess)
+ (id)oex_JSONObjectWithData:(NSData*)data error:(NSError* __autoreleasing*)error;
@end


text:
hooks
=====

My random git hooks


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using ECommon.Utilities;
using ENode.Eventing;
using ENode.Infrastructure;

namespace ENode.Domain.Impl
{
    public class DefaultAggregateRootInternalHandlerProvider : IAggregateRootInternalHandlerProvider, IAssemblyInitializer
    {
        private readonly IDictionary<Type, IDictionary<Type, Action<IAggregateRoot, IDomainEvent>>> _mappings = new Dictionary<Type, IDictionary<Type, Action<IAggregateRoot, IDomainEvent>>>();
        private readonly BindingFlags bindingFlags = BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly;
        private readonly Type[] parameterTypes = new Type[] { typeof(IAggregateRoot), typeof(IDomainEvent) };

        public void Initialize(params Assembly[] assemblies)
        {
            foreach (var assembly in assemblies)
            {
                foreach (var aggregateRootType in assembly.GetTypes().Where(ENode.Infrastructure.TypeUtils.IsAggregateRoot))
                {
                    var entries = from method in aggregateRootType.GetMethods(bindingFlags)
                                  let parameters = method.GetParameters()
                                  where method.Name == "Handle"
                                      && parameters.Length == 1
                                      && typeof(IDomainEvent).IsAssignableFrom(parameters.Single().ParameterType)
                                  select new { Method = method, EventType = parameters.Single().ParameterType };
                    foreach (var entry in entries)
                    {
                        RegisterInternalHandler(aggregateRootType, entry.EventType, entry.Method);
                    }
                }
            }
        }
        public Action<IAggregateRoot, IDomainEvent> GetInternalEventHandler(Type aggregateRootType, Type eventType)
        {
            IDictionary<Type, Action<IAggregateRoot, IDomainEvent>> eventHandlerDic;
            if (!_mappings.TryGetValue(aggregateRootType, out eventHandlerDic)) return null;
            Action<IAggregateRoot, IDomainEvent> eventHandler;
            return eventHandlerDic.TryGetValue(eventType, out eventHandler) ? eventHandler : null;
        }

        private void RegisterInternalHandler(Type aggregateRootType, Type eventType, MethodInfo eventHandler)
        {
            IDictionary<Type, Action<IAggregateRoot, IDomainEvent>> eventHandlerDic;

            if (!_mappings.TryGetValue(aggregateRootType, out eventHandlerDic))
            {
                eventHandlerDic = new Dictionary<Type, Action<IAggregateRoot, IDomainEvent>>();
                _mappings.Add(aggregateRootType, eventHandlerDic);
            }

            if (eventHandlerDic.ContainsKey(eventType))
            {
                throw new Exception(string.Format("Found duplicated event handler on aggregate, aggregate type:{0}, event type:{1}", aggregateRootType.FullName, eventType.FullName));
            }
            eventHandlerDic.Add(eventType, DelegateFactory.CreateDelegate<Action<IAggregateRoot, IDomainEvent>>(eventHandler, parameterTypes));
        }
    }
}


text:
import sys
import time
import string
import sqlite3
import requests
import BaseHTTPServer
import tweepy
import os
import smtplib
from email.mime.text import MIMEText

me = "cbuntain@coretx.net"

def loadProperties(filepath, sep='=', comment_char='#'):
    """
    Read the file passed as parameter as a properties file.
    """
    props = {}
    with open(filepath, "rt") as f:
        for line in f:
            l = line.strip()
            if l and not l.startswith(comment_char):
                key_value = l.split(sep)
                key = key_value[0].strip()
                value = sep.join(key_value[1:]).strip('" \t')
                props[key] = value
    return props

excludeSet = set(string.punctuation)
def tokenizer(tweetText):
    noPunctStr = ''.join([ch for ch in tweetText if ch not in excludeSet])
    return noPunctStr.lower().split(" ")

def makeHandler(dbConn, twitter, brokerUrl, simThreshold):
    dbCursor = dbConn.cursor()

    class BrokerHandler(BaseHTTPServer.BaseHTTPRequestHandler):

        # Handle GET requests
        def do_GET(self):

            print self.path
            if ( self.path == "/list" ):
                self.send_response(200)
                self.send_header('Content-Type','text/html; charset=utf-8')
                self.end_headers()

                self.wfile.write("<title>Submitted Tweets</title>")
                self.wfile.write("")

                for row in dbCursor.execute('SELECT tweetid, tweet FROM tweet_info ORDER BY ROWID'):
                    tweetData = row[0].split("+")
                    topic = tweetData[0]
                    tweetId = tweetData[1]
                    tweetText = row[1]

                    lineStr = u"
%s - %s : %s
" % (topic, tweetId, tweetText)
                    self.wfile.write(lineStr.encode("utf8"))

                self.wfile.write("")
            else:
                self.send_response(404)
                self.end_headers()

        # Handle POST requests
        def do_POST(self):

            self.send_response(204)
            self.send_header("Content-type", "text/html")
            self.end_headers()

            print "Received path:", self.path

            if ( self.path.startswith("/tweet") ):

                try:
                    # Format: POST /tweet/:topid/:tweetid/:clientid
                    postData = self.path.split("/")
                    topic = postData[2]
                    tweetId = postData[3]
                    uniqueTweetId = "%s+%s" % (topic, tweetId)

                    print "Tweet ID:", uniqueTweetId

                    dbCursor.execute('SELECT COUNT(*) FROM tweet_info WHERE tweetid=?', [uniqueTweetId])
                    matchCount = dbCursor.fetchone()[0]
                    print "How many times have we reported this tweet id?", matchCount

                    if ( matchCount == 0 ):
                        status = twitter.get_status(tweetId)
                        statusTokens = set(tokenizer(status.text))

                        maxSim = 0.0
                        for row in dbCursor.execute('SELECT tweetid, tweet FROM tweet_info'):
                            otherTweetText = row[1]
                            otherTokens = set(tokenizer(otherTweetText))

                            sim = float(len(statusTokens.intersection(otherTokens))) / float(len(statusTokens.union(otherTokens)))
                            maxSim = max(sim, maxSim)

                        print "Max Similarity:", maxSim

                        # Only insert in DB and push to broker if we are sufficiently dissimilar
                        if ( maxSim < simThreshold ):
                            dbCursor.execute('INSERT INTO tweet_info (path, tweetid, tweet) VALUES (?, ?, ?)', (self.path, uniqueTweetId, status.text))

                            populatedUrl = brokerUrl + self.path
                            print "Should send to:", populatedUrl

                            # send email about tweet
                            try:
                                emailMsg = MIMEText(u"New Tweet: %s - %s" % (uniqueTweetId, status.text), 'plain')
                                emailMsg['Subject'] = "New Tweet"
                                emailMsg['To'] = me
                                emailMsg['From'] = me
                                # Send the message via our own SMTP server, but don't include the
                                # envelope header.
                                s = smtplib.SMTP('localhost')
                                s.sendmail(me, [me], emailMsg.as_string())
                                s.quit()
                            except Exception as e:
                                print "Error sending email: {0}".format(e.message)

                            if ( not os.path.exists("skip_file") ):
                                resp = requests.post(populatedUrl)

                                print "Response Code:", resp.status_code
                                if ( resp.status_code != 204 ):
                                    print "Error!"
                                    print resp.headers
                                else:
                                    dbConn.commit()
                            else:
                                dbConn.commit()
                        else:
                            print "Tweet was too similar to others."

                    else:
                        print "Already submitted this tweet."
                except Exception as e:
                    raise e
                    # print "Error: {0}".format(e.message)
                    # pass

            else:
                print "Error. Malformed POST."

    return BrokerHandler

propFile = sys.argv[1]
propDict = loadProperties(propFile)
HOST_NAME = propDict["PERSONAL_BROKER_HOST"]
PORT_NUMBER = int(propDict["PERSONAL_BROKER_PORT"])
BROKER_URL = propDict["BROKER_URL"]

CONSUMER_KEY=propDict["CONSUMER_KEY"]
CONSUMER_SECRET=propDict["CONSUMER_SECRET"]
ACCESS_TOKEN=propDict["ACCESS_TOKEN"]
ACCESS_TOKEN_SECRET=propDict["ACCESS_TOKEN_SECRET"]

SIM_THRESHOLD=float(propDict["SIM_THRESHOLD"])

# Create the database for storing tweet info we submit
conn = sqlite3.connect("tweet_data.db")

# Create table
c = conn.cursor()
c.execute('''CREATE TABLE IF NOT EXISTS tweet_info (path TEXT, tweetid TEXT, tweet TEXT)''')
conn.commit()

# Connect to twitter
auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
auth.set_access_token(ACCESS_TOKEN, ACCESS_TOKEN_SECRET)

api = tweepy.API(auth)

# Test API
status = api.get_status("738418531520352258")
print status.text

# Create our HTTP server
server_class = BaseHTTPServer.HTTPServer
httpd = server_class((HOST_NAME, PORT_NUMBER), makeHandler(conn, api, BROKER_URL, SIM_THRESHOLD))
print time.asctime(), "Server Starts - %s:%s" % (HOST_NAME, PORT_NUMBER)

try:
    httpd.serve_forever()
except KeyboardInterrupt:
    pass

httpd.server_close()


text:
module Train
  def self.src_root
    File.expand_path(File.join(__FILE__, "..", "..", ".."))
  end
end


text:
package org.sleuthkit.autopsy.corecomponents;

import java.awt.Cursor;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.dnd.DnDConstants;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import org.sleuthkit.autopsy.coreutils.Logger;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
import org.netbeans.swing.outline.DefaultOutlineModel;
import org.openide.explorer.ExplorerManager;
import org.openide.explorer.view.OutlineView;
import org.openide.nodes.AbstractNode;
import org.openide.nodes.Children;
import org.openide.nodes.Node;
import org.openide.nodes.Node.Property;
import org.openide.nodes.Node.PropertySet;
import org.openide.nodes.Sheet;
import org.sleuthkit.autopsy.corecomponentinterfaces.DataResultViewer;

/**
 * DataResult sortable table viewer
 */
// @@@ Restore implementation of DataResultViewerTable as a DataResultViewer
// service provider when DataResultViewers can be made compatible with node
// multiple selection actions.
//@ServiceProvider(service = DataResultViewer.class)
public class DataResultViewerTable extends AbstractDataResultViewer {

    private String firstColumnLabel = "Name";
    private Set<Property> propertiesAcc = new LinkedHashSet<>();
    private static final Logger logger = Logger.getLogger(DataResultViewerTable.class.getName());

    /**
     * Creates a DataResultViewerTable object that is compatible with node
     * multiple selection actions.
     */
    public DataResultViewerTable(ExplorerManager explorerManager) {
        super(explorerManager);
        initialize();
    }

    /**
     * Creates a DataResultViewerTable object that is NOT compatible with node
     * multiple selection actions.
     */
    public DataResultViewerTable() {
        initialize();
    }

    private void initialize() {
        initComponents();

        OutlineView ov = ((OutlineView) this.tableScrollPanel);
        ov.setAllowedDragActions(DnDConstants.ACTION_NONE);
        ov.setAllowedDropActions(DnDConstants.ACTION_NONE);

        ov.getOutline().setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);

        // don't show the root node
        ov.getOutline().setRootVisible(false);
        ov.getOutline().setDragEnabled(false);
    }

    /**
     * Expand node
     *
     * @param n Node to expand
     */
    @Override
    public void expandNode(Node n) {
        super.expandNode(n);

        if (this.tableScrollPanel != null) {
            OutlineView ov = ((OutlineView) this.tableScrollPanel);
            ov.expandNode(n);
        }
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        tableScrollPanel = new OutlineView(this.firstColumnLabel);

        //new TreeTableView()
        tableScrollPanel.addComponentListener(new java.awt.event.ComponentAdapter() {
            public void componentResized(java.awt.event.ComponentEvent evt) {
                tableScrollPanelComponentResized(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(tableScrollPanel, javax.swing.GroupLayout.DEFAULT_SIZE, 691, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(tableScrollPanel, javax.swing.GroupLayout.DEFAULT_SIZE, 366, Short.MAX_VALUE)
        );
    }// </editor-fold>//GEN-END:initComponents

    private void tableScrollPanelComponentResized(java.awt.event.ComponentEvent evt) {//GEN-FIRST:event_tableScrollPanelComponentResized
    }//GEN-LAST:event_tableScrollPanelComponentResized
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JScrollPane tableScrollPanel;
    // End of variables declaration//GEN-END:variables

    /**
     * Gets regular Bean property set properties from first child of Node.
     *
     * @param parent Node with at least one child to get properties from
     * @return Properties,
     */
    private Node.Property[] getChildPropertyHeaders(Node parent) {
        Node firstChild = parent.getChildren().getNodeAt(0);

        if (firstChild == null) {
            throw new IllegalArgumentException("Couldn't get a child Node from the given parent.");
        } else {
            for (PropertySet ps : firstChild.getPropertySets()) {
                if (ps.getName().equals(Sheet.PROPERTIES)) {
                    return ps.getProperties();
                }
            }

            throw new IllegalArgumentException("Child Node doesn't have the regular PropertySet.");
        }
    }

    /**
     * Gets regular Bean property set properties from all first children and,
     * recursively, subchildren of Node. Note: won't work out the box for lazy
     * load - you need to set all children props for the parent by hand
     *
     * @param parent Node with at least one child to get properties from
     * @return Properties,
     */
    private Node.Property[] getAllChildPropertyHeaders(Node parent) {
        Node firstChild = parent.getChildren().getNodeAt(0);

        Property[] properties = null;

        if (firstChild == null) {
            throw new IllegalArgumentException("Couldn't get a child Node from the given parent.");
        } else {
            Set<Property> allProperties = new LinkedHashSet<Property>();
            while (firstChild != null) {
                for (PropertySet ps : firstChild.getPropertySets()) {
                    //if (ps.getName().equals(Sheet.PROPERTIES)) {
                    //return ps.getProperties();
                    final Property[] props = ps.getProperties();
                    final int propsNum = props.length;
                    for (int i = 0; i < propsNum; ++i) {
                        allProperties.add(props[i]);
                    }
                    //}
                }
                firstChild = firstChild.getChildren().getNodeAt(0);
            }

            properties = allProperties.toArray(new Property[0]);
            //throw new IllegalArgumentException("Child Node doesn't have the regular PropertySet.");
        }
        return properties;

    }

    /**
     * Gets regular Bean property set properties from all children and,
     * recursively, subchildren of Node. Note: won't work out the box for lazy
     * load - you need to set all children props for the parent by hand
     *
     * @param parent Node with at least one child to get properties from
     * @param rows max number of rows to retrieve properties for (can be used
     * for memory optimization)
     */
    private void getAllChildPropertyHeadersRec(Node parent, int rows) {
        Children children = parent.getChildren();
        int total = Math.min(rows, children.getNodesCount());
        for (int i = 0; i < total; i++) {
            Node child = children.getNodeAt(i);
            for (PropertySet ps : child.getPropertySets()) {
                //if (ps.getName().equals(Sheet.PROPERTIES)) {
                //return ps.getProperties();
                final Property[] props = ps.getProperties();
                final int propsNum = props.length;
                for (int j = 0; j < propsNum; ++j) {
                    propertiesAcc.add(props[j]);
                }
                //}
            }
            getAllChildPropertyHeadersRec(child, rows);
        }
    }

    @Override
    public boolean isSupported(Node selectedNode) {
        return true;
    }

    @Override
    public void setNode(Node selectedNode) {
        // change the cursor to "waiting cursor" for this operation
        this.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
        try {
            boolean hasChildren = false;

            if (selectedNode != null) {
                hasChildren = selectedNode.getChildren().getNodesCount() > 0;
            }

            // if there's no selection node, do nothing
            if (hasChildren) {
                Node root = selectedNode;

                //wrap to filter out children
                //note: this breaks the tree view mode in this generic viewer,
                //so wrap nodes earlier if want 1 level view
                //if (!(root instanceof TableFilterNode)) {
                ///    root = new TableFilterNode(root, true);
                //}

                em.setRootContext(root);

                final OutlineView ov = ((OutlineView) this.tableScrollPanel);

                propertiesAcc.clear();

                this.getAllChildPropertyHeadersRec(selectedNode, 100);
                List<Node.Property> props = new ArrayList<Node.Property>(propertiesAcc);
                if (props.size() > 0) {
                    Node.Property prop = props.remove(0);
                    ((DefaultOutlineModel) ov.getOutline().getOutlineModel()).setNodesColumnLabel(prop.getDisplayName());
                }

                // *********** Make the TreeTableView to be sortable ***************

                //First property column is sortable, but also sorted initially, so
                //initially this one will have the arrow icon:
                if (props.size() > 0) {
                    props.get(0).setValue("TreeColumnTTV", Boolean.TRUE); // Identifies special property representing first (tree) column.
                    props.get(0).setValue("SortingColumnTTV", Boolean.TRUE); // TreeTableView should be initially sorted by this property column.
                }

                // The rest of the columns are sortable, but not initially sorted,
                // so initially will have no arrow icon:
                String[] propStrings = new String[props.size() * 2];
                for (int i = 0; i < props.size(); i++) {
                    props.get(i).setValue("ComparableColumnTTV", Boolean.TRUE);
                    propStrings[2 * i] = props.get(i).getName();
                    propStrings[2 * i + 1] = props.get(i).getDisplayName();
                }

                ov.setPropertyColumns(propStrings);
                // *****************************************************************

                //            // set the first entry
                //            Children test = root.getChildren();
                //            Node firstEntryNode = test.getNodeAt(0);
                //            try {
                //                this.getExplorerManager().setSelectedNodes(new Node[]{firstEntryNode});
                //            } catch (PropertyVetoException ex) {}

                // show the horizontal scroll panel and show all the content & header

                int totalColumns = props.size();

                //int scrollWidth = ttv.getWidth();
                int margin = 4;
                int startColumn = 1;
                ov.getOutline().setAutoResizeMode(JTable.AUTO_RESIZE_OFF);

                // get first 100 rows values for the table
                Object[][] content = null;
                content = getRowValues(selectedNode, 100);

                if (content != null) {
                    // get the fontmetrics
                    final Graphics graphics = ov.getGraphics();
                    if (graphics != null) {
                        final FontMetrics metrics = graphics.getFontMetrics();

                        // for the "Name" column
                        int nodeColWidth = Math.min(getMaxColumnWidth(0, metrics, margin, 40, firstColumnLabel, content), 250); // Note: 40 is the width of the icon + node lines. Change this value if those values change!
                        ov.getOutline().getColumnModel().getColumn(0).setPreferredWidth(nodeColWidth);

                        // get the max for each other column
                        for (int colIndex = startColumn; colIndex <= totalColumns; colIndex++) {
                            int colWidth = Math.min(getMaxColumnWidth(colIndex, metrics, margin, 8, props, content), 350);
                            ov.getOutline().getColumnModel().getColumn(colIndex).setPreferredWidth(colWidth);
                        }
                    }
                }

                // if there's no content just auto resize all columns
                if (!(content.length > 0)) {
                    // turn on the auto resize
                    ov.getOutline().setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
                }

            } else {
                final OutlineView ov = ((OutlineView) this.tableScrollPanel);
                Node emptyNode = new AbstractNode(Children.LEAF);
                em.setRootContext(emptyNode); // make empty node
                ov.getOutline().setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
                ov.setPropertyColumns(); // set the empty property header
            }
        } finally {
            this.setCursor(null);
        }
    }

    private static Object[][] getRowValues(Node node, int rows) {
        // how many rows are we returning
        int maxRows = Math.min(rows, node.getChildren().getNodesCount());

        Object[][] objs = new Object[maxRows][];

        for (int i = 0; i < maxRows; i++) {
            PropertySet[] props = node.getChildren().getNodeAt(i).getPropertySets();
            if (props.length == 0) //rare special case
            {
                continue;
            }
            Property[] property = props[0].getProperties();
            objs[i] = new Object[property.length];

            for (int j = 0; j < property.length; j++) {
                try {
                    objs[i][j] = property[j].getValue();
                } catch (IllegalAccessException ignore) {
                    objs[i][j] = "n/a";
                } catch (InvocationTargetException ignore) {
                    objs[i][j] = "n/a";
                }
            }
        }
        return objs;
    }

    @Override
    public String getTitle() {
        return "Table";
    }

    @Override
    public DataResultViewer createInstance() {
        return new DataResultViewerTable();
    }

    /**
     * Gets the max width of the column from the given index, header, and table.
     *
     * @param index the index of the column on the table / header
     * @param metrics the font metrics that this component use
     * @param margin the left/right margin of the column
     * @param padding the left/right padding of the column
     * @param header the property headers of the table
     * @param table the object table
     * @return max the maximum width of the column
     */
    private int getMaxColumnWidth(int index, FontMetrics metrics, int margin, int padding, List<Node.Property> header, Object[][] table) {
        // set the tree (the node / names column) width
        String headerName = header.get(index - 1).getDisplayName();

        return getMaxColumnWidth(index, metrics, margin, padding, headerName, table);
    }

    /**
     * Gets the max width of the column from the given index, header, and table.
     *
     * @param index the index of the column on the table / header
     * @param metrics the font metrics that this component use
     * @param margin the left/right margin of the column
     * @param padding the left/right padding of the column
     * @param header the column header for the comparison
     * @param table the object table
     * @return max the maximum width of the column
     */
    private synchronized int getMaxColumnWidth(int index, FontMetrics metrics, int margin, int padding, String header, Object[][] table) {
        // set the tree (the node / names column) width
        String headerName = header;
        int headerWidth = metrics.stringWidth(headerName); // length of the header
        int colWidth = 0;

        // Get maximum width of column data
        for (int i = 0; i < table.length; i++) {
            if (table[i] == null || index >= table[i].length) {
                continue;
            }
            String test = table[i][index].toString();
            colWidth = Math.max(colWidth, metrics.stringWidth(test));
        }

        colWidth += padding; // add the padding on the most left gap
        headerWidth += 8; // add the padding to the header (change this value if the header padding value is changed)

        // Set the width
        int width = Math.max(headerWidth, colWidth);
        width += 2 * margin; // Add margin

        return width;
    }

    @Override
    public void clearComponent() {
        this.tableScrollPanel.removeAll();
        this.tableScrollPanel = null;

        super.clearComponent();
    }
}


text:
package net.stevechaloner.intellijad.decompilers;

import com.intellij.openapi.vfs.VirtualFile;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import net.stevechaloner.intellijad.IntelliJadConstants;

import org.jetbrains.annotations.NotNull;

/**
 * Factory for creating {@link FileSystemDecompilationDescriptor}s based on a virtual file representing the target class.
 *
 * @author Steve Chaloner
 */
class FileSystemDecompilationDescriptorFactory extends DecompilationDescriptorFactory
{
    /**
     * The pattern for a package declaration within a class.
     */
    private static final Pattern PACKAGE_PATTERN = Pattern.compile("package [\\w|\\.]*;");

    /** {@inheritDoc} */
    @NotNull
    public DecompilationDescriptor create(@NotNull VirtualFile target)
    {
        return new FileSystemDecompilationDescriptor(target);
    }

    /** {@inheritDoc} */
    public void update(@NotNull DecompilationDescriptor dd,
                       @NotNull String classContent)
    {
        Matcher packageNameMatcher = PACKAGE_PATTERN.matcher(classContent);
        if (packageNameMatcher.find())
        {
            String packageName = classContent.substring("package ".length() + packageNameMatcher.start(),
                                                        packageNameMatcher.end() - 1);
            dd.setPackageName(packageName);
            String asPath = packageName.replaceAll("\\.", "/");
            if (!asPath.endsWith("/"))
            {
                asPath = asPath + '/';
            }
            dd.setPackageNameAsPath(asPath);
            dd.setFqName(packageName + '.' + dd.getClassName());
            dd.setFqNameAsPath(asPath + dd.getClassName() + IntelliJadConstants.DOT_JAVA_EXTENSION);
        }
        else
        {
            dd.setPackageName("");
            dd.setPackageNameAsPath("");
            dd.setFqName(dd.getClassName());
            dd.setFqNameAsPath(dd.getClassName() + IntelliJadConstants.DOT_JAVA_EXTENSION);
        }
    }

}


text:
<?php

namespace App\Transformers;

use App\Models\Department;
use League\Fractal\TransformerAbstract;

class DepartmentTransformer extends TransformerAbstract
{
    public function transform(Department $department)
    {
        return [
            'id' => $department->id,
            'title' => $department->title,
            'created_at' => $department->created_at->toDateTimeString(),
            'updated_at' => $department->updated_at->toDateTimeString()
        ];
    }
}


text:
ACCEPTED

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

#### Published in
null

#### Original name
Roegneria sylvatica Keng & S.L.Chen

### Remarks
null


text:
package org.apache.flink.graph.types.valuearray;

import org.apache.flink.api.common.typeutils.SimpleTypeSerializerSnapshot;
import org.apache.flink.api.common.typeutils.TypeSerializerSnapshot;
import org.apache.flink.api.common.typeutils.base.TypeSerializerSingleton;
import org.apache.flink.core.memory.DataInputView;
import org.apache.flink.core.memory.DataOutputView;

import java.io.IOException;

/**
 * Specialized serializer for {@code ShortValueArray}.
 */
public final class ShortValueArraySerializer extends TypeSerializerSingleton<ShortValueArray> {

	private static final long serialVersionUID = 1L;

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

	@Override
	public ShortValueArray createInstance() {
		return new ShortValueArray();
	}

	@Override
	public ShortValueArray copy(ShortValueArray from) {
		return copy(from, new ShortValueArray());
	}

	@Override
	public ShortValueArray copy(ShortValueArray from, ShortValueArray reuse) {
		reuse.setValue(from);
		return reuse;
	}

	@Override
	public int getLength() {
		return -1;
	}

	@Override
	public void serialize(ShortValueArray record, DataOutputView target) throws IOException {
		record.write(target);
	}

	@Override
	public ShortValueArray deserialize(DataInputView source) throws IOException {
		return deserialize(new ShortValueArray(), source);
	}

	@Override
	public ShortValueArray deserialize(ShortValueArray reuse, DataInputView source) throws IOException {
		reuse.read(source);
		return reuse;
	}

	@Override
	public void copy(DataInputView source, DataOutputView target) throws IOException {
		ShortValueArray.copyInternal(source, target);
	}

	// ------------------------------------------------------------------------

	@Override
	public TypeSerializerSnapshot<ShortValueArray> snapshotConfiguration() {
		return new ShortValueArraySerializerSnapshot();
	}

	/**
	 * Serializer configuration snapshot for compatibility and format evolution.
	 */
	@SuppressWarnings("WeakerAccess")
	public static final class ShortValueArraySerializerSnapshot extends SimpleTypeSerializerSnapshot<ShortValueArray> {

		public ShortValueArraySerializerSnapshot() {
			super(ShortValueArraySerializer::new);
		}
	}
}


text:
namespace enterprise_connectors {

// Contains all known key generation trust levels (generated via TPM or not).
// These values are persisted to logs and should not be renumbered. Please
// update the DTKeyTrustLevel enum in enums.xml when adding a new step here.
enum class DTKeyTrustLevel {
  kUnspecified = 0,
  kTpm = 1,
  kOs = 2,
  kMaxValue = kOs,
};

// Contains all known key types, which represents the algorithms used to
// generate the Device Trust signing key. These values are persisted to logs and
// should not be renumbered. Please update the DTKeyType enum in enums.xml when
// adding a new step here.
enum class DTKeyType {
  kRsa = 0,
  kEc = 1,
  kMaxValue = kEc,
};

// Possible outcomes of the key rotation process. These
// values are persisted to logs and should not be renumbered. Please update
// the DTKeyRotationResult enum in enums.xml when adding a new step here.
enum class DTKeyRotationResult {
  kSucceeded = 0,
  kFailed = 1,
  kTimedOut = 2,
  kMaxValue = kTimedOut,
};

// Logs the `key_metadata` trust level and type. If it is not defined
// (i.e. absl::nullopt), nothing is logged.
void LogKeyLoadingResult(
    absl::optional<DeviceTrustKeyManager::KeyMetadata> key_metadata);

// Logs the key rotation result based on the value of `status`. Also, if
// `had_nonce` is false, it will be logged as a key creation flow.
void LogKeyRotationResult(bool had_nonce, KeyRotationCommand::Status status);

}  // namespace enterprise_connectors

#endif  // CHROME_BROWSER_ENTERPRISE_CONNECTORS_DEVICE_TRUST_KEY_MANAGEMENT_BROWSER_METRICS_UTILS_H_


text:
layout: post
title: Please fail... but do it fast
date: 2013-10-03T06:00:00.000Z
author: Marcus Hammarberg
tags:
  - Lean
  - Agile- ContinuousDelivery
modified_time: 2013-10-03T06:00:04.051Z
thumbnail: >-
  http://3.bp.blogspot.com/-NyVQT4IS96s/UkwXuIhh2WI/AAAAAAAABso/ZqeDZVFt5DU/s72-c/Screen+Shot+2013-10-02+at+14.52.05+.png
blogger_id: tag:blogger.com,1999:blog-36533086.post-1375963835292412831
blogger_orig_url: http://www.marcusoft.net/2013/10/failfast.html
---

|                                                                                |
|:---------------------------------------------------------------------------------------------------------------------------------------------------------------------:|
|                                                                                |
|                                             Photo by Klaus Wachsmuth                                                                   |

I had the great pleasure to do my military service in the
Swedish Army Band, that at the time (1992) was made
up of conscripts. Not only did I get to wear stuff like the picture to
the left and play in an awesomely great band, but also did we travel
Europe and played, among other places the Casino in Monaco. It was a
awesome year in many regards and I tied friendship-knots with a lot of
people that still get to meet today.

On our last day in the band there were a lot of tears and saying
farewell to friends and officers that had taken care of us. Through all
the emotions that day I still remember one thing that an officer said as
his part of his farewell speech:

> Fellas - don't fear mistakes. By all means, fail. But try to steer
> away from irreversible mistakes.

I'll tell you right away that I didn't fully understood that then. And
maybe not now either, but let me take you through some thoughts on this
that have helped me during the 20+ years since he said that to me. And
how I've during the last years have found another, simpler approach.

What I think that our captain tried to tell us
was something about risk. Things will end up failing. That's not a
biggie if that doesn't cost you too much. If you forgot to pick up
milk... so what?
No milk today and but you can pick up some
tomorrow.

But if you forget to pick up your kid from football training... there
will be some bad consequences (it actually happened to a dad in Sweden a
few months back - could have been me). So for important things like that
you have to put in some kind of warning system that helps you to
remember that. The higher the cost of forgetting the thing the more
warning systems and help to remember it we need.

This is basic risk management and is brilliantly described by
Dan North in
this
presentation that often refer people to. Dan tells us that risk has
two components; cost and likelihood. If something is very costly (to
miss for example) and also has a big likelihood to occur, well then you
sure want to think about it. Deeply. And long. Before you try to do
something about it.

If it's not that costly and not that likely either... well go on... just
do it!

For another combination you have to make up your own mind. The important
thing is that you need to think and make an opinion for yourself.

In the diagram to the right you see my very risk friendly decision
matrix. Don't use this for all your decisions.

### Failing faster

However... I'm now an older man with more experience. I'm still not
wiser and I definitely don't say that I'm wiser than my captain. He told
us to never say that to him, so I better not.

But I think differently about matter like these nowadays. I think the
real trick lies in failing as fast as possible and make corrections. In
fact, I'll go so far as to say that in business the future belongs to
the people that can fail and iterate the fastest. It's of course not
only me that says that (then I wouldn't believe in it) so please read up
on the Lean Startup
movement that is swiping the business world, both for startups but
also big enterprises.

What I mean is that if you can iterate fast the cost of failing goes
down. Me driving the wrong way for 10 minutes is not as costly as me
driving the wrong way for 10 hours. So I try to check that I'm driving
the right way often (if I don't know the way already).

I work with a great product owner right now here at
Tradera (yes, it's
you Kevin) that have told his team roughly this:

> You don't need to give me any estimates and plans. I have great fate
> in you and think that you probably know better than me what is the
> next great thing to do. Hey - it's even ok that you fail and end up
> doing the wrong thing. As long as you fail fast and learn from it.

> I can cover the cost of you doing the wrong thing for two weeks. It's
> not ok that you fail for three months and then come back to me and
> say: it can't be done. Let's fail faster than that.

|                                                                                |
|:-----------------------------------------------------------------------------------------------:|
|                                           |
|                                             From HowStuffWorks                                 |

Awesome! I'd love an product owner like that. It also acknowledges the
fact that we don't know what the best route to success is, or even what
we should build to best serve our customers. To know that we have to try
it out in a real-life scenario, with real customers, doing real things.
And then iterate new versions to correct our early hypothesis on what we
thought would make a big business impact.

Now... where have I heard this kind of reasoning before... I'm sure it
was done by some clever guys... Ah yes - all scientists all over the
world since
Aristotle and up to today works this way. It's
called the the scientific method and has proven useful to them. It
might be to me and you too.

### Conclusion

I suggest that rather than to try to outsmart, outplan, outthink and
handle every possible risk and uncertainty we should instead try to
redesign our work so that we fail faster. Yes, you read that correctly,
I said **change the way we work** in order to fail faster. I think the
future belongs to the people and companies that can iterate fast.

What can I do to iterate faster? To fail faster? How can I faster get to
know that I'm going the wrong way? That I'm about to forget to pick up
my kid? That my code is not only used but also making an business
impact? What are the smallest steps I can take to learn more?

Most likely I haven't told you anything that you couldn't have read
somewhere else. And even more likely there's theories, diagrams and
formulas that can prove this. But this was more a kinda of "I feel this"
post. I long for you to point me to the theories that support this. Or
falsifies it. Please tell me fast - I need to fail. Faster.


text:
using System;
using System.Collections.Generic;
using System.Net.Http;
using Microsoft.Extensions.Logging;
using Moq;
using StockportWebapp.Http;
using Xunit;

namespace StockportWebappTests_Unit.Unit.Http
{
    public class LoggingHttpClientTest
    {
        readonly FakeHttpClient _fakeHttpClient = new FakeHttpClient();

        [Fact]
        public async void HandlesNoResponseFromRemote()
        {
            _fakeHttpClient.For("a url").Throw(
                new AggregateException(new HttpRequestException()));
            var logger = new Mock<ILogger<LoggingHttpClient>>().Object;
            var httpClient = new LoggingHttpClient( _fakeHttpClient, logger);
            HttpResponse response = await httpClient.Get("a url", new Dictionary<string, string>());

            Assert.Equal(503, response.StatusCode);
            Assert.Equal("Failed to invoke the requested resource", response.Error);
        }

        [Fact]
        public async void ReturnsSuccessfulResponseFromRemote()
        {
            _fakeHttpClient.For("a url").Return(HttpResponse.Successful(200, "some data"));
            var logger = new Mock<ILogger<LoggingHttpClient>>().Object;
            var httpClient = new LoggingHttpClient(_fakeHttpClient, logger);
            HttpResponse response = await httpClient.Get("a url", new Dictionary<string, string>());

            Assert.Equal(200, response.StatusCode);
        }
    }
}


text:
package at.linuxtage.companion.adapters;

import android.util.SparseArray;
import android.view.ViewGroup;

import java.util.Arrays;
import java.util.List;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

/**
 * Adapter which concatenates the items of multiple adapters.
 * Doesn't support stable ids, but properly delegates changes notifications.
 * <p>
 * Adapters may provide multiple view types but they must not overlap.
 * It's recommended to always use the item layout id as view type.
 *
 * @author Christophe Beyls
 */
public class ConcatAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

	private final RecyclerView.Adapter<RecyclerView.ViewHolder>[] adapters;
	private final RecyclerView.AdapterDataObserver[] adapterObservers;
	final int[] offsets;
	int totalItemCount = -1;
	private final SparseArray<RecyclerView.Adapter<RecyclerView.ViewHolder>> viewTypeAdapters = new SparseArray<>();

	private class InternalObserver extends RecyclerView.AdapterDataObserver {

		private final int adapterIndex;

		InternalObserver(int adapterIndex) {
			this.adapterIndex = adapterIndex;
		}

		@Override
		public void onChanged() {
			totalItemCount = -1;
			notifyDataSetChanged();
		}

		@Override
		public void onItemRangeChanged(int positionStart, int itemCount) {
			if (totalItemCount != -1) {
				notifyItemRangeChanged(positionStart + offsets[adapterIndex], itemCount);
			}
		}

		@Override
		public void onItemRangeChanged(int positionStart, int itemCount, Object payload) {
			if (totalItemCount != -1) {
				notifyItemRangeChanged(positionStart + offsets[adapterIndex], itemCount, payload);
			}
		}

		@Override
		public void onItemRangeInserted(int positionStart, int itemCount) {
			if (totalItemCount != -1) {
				for (int i = adapterIndex + 1, size = offsets.length; i < size; ++i) {
					offsets[i] += itemCount;
				}
				totalItemCount += itemCount;
				notifyItemRangeInserted(positionStart + offsets[adapterIndex], itemCount);
			}
		}

		@Override
		public void onItemRangeRemoved(int positionStart, int itemCount) {
			if (totalItemCount != -1) {
				for (int i = adapterIndex + 1, size = offsets.length; i < size; ++i) {
					offsets[i] -= itemCount;
				}
				totalItemCount -= itemCount;
				notifyItemRangeRemoved(positionStart + offsets[adapterIndex], itemCount);
			}
		}

		@Override
		public void onItemRangeMoved(int fromPosition, int toPosition, int itemCount) {
			if (totalItemCount != -1) {
				final int offset = offsets[adapterIndex];
				notifyItemMoved(fromPosition + offset, toPosition + offset);
			}
		}
	}

	@SafeVarargs
	@SuppressWarnings("unchecked")
	public ConcatAdapter(RecyclerView.Adapter<? extends RecyclerView.ViewHolder>... adapters) {
		this.adapters = (RecyclerView.Adapter<RecyclerView.ViewHolder>[]) adapters;
		final int size = adapters.length;
		adapterObservers = new RecyclerView.AdapterDataObserver[size];
		for (int i = 0; i < size; ++i) {
			adapterObservers[i] = new InternalObserver(i);
		}
		offsets = new int[size];
	}

	private int getAdapterIndexForPosition(int position) {
		int index = Arrays.binarySearch(offsets, position);
		if (index < 0) {
			return ~index - 1;
		}
		// If the array contains multiple identical values (empty adapters), return the index of the last one
		do {
			++index;
		}
		while ((index < offsets.length) && (offsets[index] == position));
		return --index;
	}

	@Override
	public int getItemViewType(int position) {
		final int index = getAdapterIndexForPosition(position);
		RecyclerView.Adapter<RecyclerView.ViewHolder> adapter = adapters[index];
		int viewType = adapter.getItemViewType(position - offsets[index]);
		if (viewTypeAdapters.get(viewType) == null) {
			viewTypeAdapters.put(viewType, adapter);
		}
		return viewType;
	}

	@NonNull
	@Override
	public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
		return viewTypeAdapters.get(viewType).onCreateViewHolder(parent, viewType);
	}

	@Override
	public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
		final int index = getAdapterIndexForPosition(position);
		adapters[index].onBindViewHolder(holder, position - offsets[index]);
	}

	@Override
	public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position, @NonNull List<Object> payloads) {
		final int index = getAdapterIndexForPosition(position);
		adapters[index].onBindViewHolder(holder, position - offsets[index], payloads);
	}

	@Override
	public int getItemCount() {
		if (totalItemCount == -1) {
			int count = 0;
			for (int i = 0, size = adapters.length; i < size; ++i) {
				offsets[i] = count;
				count += adapters[i].getItemCount();
			}
			totalItemCount = count;
		}
		return totalItemCount;
	}

	@Override
	public void registerAdapterDataObserver(@NonNull RecyclerView.AdapterDataObserver observer) {
		if (!hasObservers()) {
			for (int i = 0, size = adapters.length; i < size; ++i) {
				adapters[i].registerAdapterDataObserver(adapterObservers[i]);
			}
		}
		super.registerAdapterDataObserver(observer);
	}

	@Override
	public void unregisterAdapterDataObserver(@NonNull RecyclerView.AdapterDataObserver observer) {
		super.unregisterAdapterDataObserver(observer);
		if (!hasObservers()) {
			for (int i = 0, size = adapters.length; i < size; ++i) {
				adapters[i].unregisterAdapterDataObserver(adapterObservers[i]);
			}
		}
	}

	@Override
	public void onAttachedToRecyclerView(@NonNull RecyclerView recyclerView) {
		for (RecyclerView.Adapter<RecyclerView.ViewHolder> adapter : adapters) {
			adapter.onAttachedToRecyclerView(recyclerView);
		}
	}

	@Override
	public void onDetachedFromRecyclerView(@NonNull RecyclerView recyclerView) {
		for (RecyclerView.Adapter<RecyclerView.ViewHolder> adapter : adapters) {
			adapter.onDetachedFromRecyclerView(recyclerView);
		}
	}

	@Override
	public void onViewAttachedToWindow(@NonNull RecyclerView.ViewHolder holder) {
		viewTypeAdapters.get(holder.getItemViewType()).onViewAttachedToWindow(holder);
	}

	@Override
	public void onViewDetachedFromWindow(@NonNull RecyclerView.ViewHolder holder) {
		viewTypeAdapters.get(holder.getItemViewType()).onViewDetachedFromWindow(holder);
	}

	@Override
	public void onViewRecycled(@NonNull RecyclerView.ViewHolder holder) {
		viewTypeAdapters.get(holder.getItemViewType()).onViewRecycled(holder);
	}

	@Override
	public boolean onFailedToRecycleView(@NonNull RecyclerView.ViewHolder holder) {
		return viewTypeAdapters.get(holder.getItemViewType()).onFailedToRecycleView(holder);
	}
}


text:
<!--STYLESHEET-->
<!--=================================================-->

<!--Open Sans Font [ OPTIONAL ] -->
<link href="http://fonts.googleapis.com/css?family=Open+Sans:300,400,600,700&subset=latin" rel="stylesheet">
<!--Bootstrap Stylesheet [ REQUIRED ]-->
<link href="{{ url('admin') }}/css/bootstrap.min.css" rel="stylesheet">
<!--Nifty Stylesheet [ REQUIRED ]-->
<link href="{{ url('admin') }}/css/nifty.min.css" rel="stylesheet">
@if($privilege->theme !== 'theme-dark')
  <link href="{{ url('admin') }}/css/themes/{{ $privilege->theme }}.min.css" rel="stylesheet">
@endif
<!--Font Awesome [ OPTIONAL ]-->
<link href="{{ url('admin') }}/plugins/font-awesome/css/font-awesome.min.css" rel="stylesheet">
<!--Animate.css [ OPTIONAL ]-->
<link href="{{ url('admin') }}/plugins/animate-css/animate.min.css" rel="stylesheet">
<!--Morris.js [ OPTIONAL ]-->
<link href="{{ url('admin') }}/plugins/morris-js/morris.min.css" rel="stylesheet">
<!--Switchery [ OPTIONAL ]-->
<link href="{{ url('admin') }}/plugins/switchery/switchery.min.css" rel="stylesheet">
<!--Bootstrap Select [ OPTIONAL ]-->
<link href="{{ url('admin') }}/plugins/bootstrap-select/bootstrap-select.min.css" rel="stylesheet">
<!--Demo script [ DEMONSTRATION ]-->
<link href="{{ url('admin') }}/css/demo/nifty-demo.min.css" rel="stylesheet">
@stack('style')


text:
class VRDemoSteamVRConfigurator : public l4Singleton<VRDemoSteamVRConfigurator>
{
public:
    typedef std::map<std::string, Json::Value> PROPERTY_MAP;
    VRDemoSteamVRConfigurator();
    ~VRDemoSteamVRConfigurator();
    bool init();
    bool isActive() { return m_inited; };
    // it may require restarting of SteamVR to take effect,
    // we'll pop a promote message box.
    bool applySettings();
    // it may require restarting of SteamVR to take effect,.
    // but we will not pop a promote message box, try not to distube users
    bool restoreSettings();
    static const std::string SETTINGS_FILE_NAME;
    static const std::string SETTINGS_FILE_OLD_POSTFIX;
    static const std::string SETTINGS_FILE_RELATIVE_PATH;
    static const std::string SETTINGS_SECTION_NAME;

    static const std::string STEAM_VR_FILE_RELATIVE_PATH;
    static const std::string STEAM_VR_PROCESS_NAME;
    static const std::string STEAM_VR_REG_KEY;
private:
    bool loadConfigurations();
    void cleanObject(Json::Value &object);
    void restartSteamVR(DWORD processID);
    DWORD findSteamVRProcessID();
    Json::Value getSettingsItemValue(Json::Value &root, const std::string path);
    bool setSettingItemValue(Json::Value &root, const std::string path, const Json::Value& value);
    bool saveJsonToFile(const Json::Value &root, const std::string& filePath);

    bool m_inited = false;
    std::string m_settingFilePath;
    std::string m_steamVRFilePath;
    // NOTE: to simplify, "." is used for path delimiter
    // it will fail, if a key name in the path contain "."
    PROPERTY_MAP m_targetSettings;
    PROPERTY_MAP m_oldSettings;
};


text:
const {Pleasure} = require("../pleasure-admin-panel/js/pleasure");
const {Layout} = require("../pleasure-admin-panel/js/layout");
window._ = require('lodash');
let $ = require("jquery");
require('jquery-ui');
require('jquery-ui/ui/widgets/sortable');
require('jquery-ui/ui/disable-selection');
require('icheck');
require('bootstrap');
require('bootstrap-select');

/**
 * We'll load jQuery and the Bootstrap jQuery plugin which provides support
 * for JavaScript based Bootstrap features such as modals and tabs. This
 * code may be modified to fit the specific needs of your application.
 */

try {
    window.Popper = require('popper.js').default;
    window.$ = window.jQuery = $ = require('jquery');
} catch (e) {
    console.error(e);
}

$(document).ready(function () {
    Pleasure.init();
    Layout.init();
    $("[id^=tooltip-]").tooltip();
    setTimeout(function () {
        /*Close any flash message after some time*/
        $(".alert-dismissable").fadeTo(4000, 500).slideUp(500, function () {
            $(".alert-dismissable").alert('close');
        });
    }, 5000);

    $("input[type='checkbox'], input[type='radio']").iCheck({
        checkboxClass: 'icheckbox_flat-blue',
        radioClass: 'iradio_flat-blue'
    });
});


text:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

/**
 * CodeIgniter CRUD Model
 *
 * A basic and resulable CRUD model for working with databases in CodeIgniter
 *
 * @package         CodeIgniter
 * @subpackage      Models
 * @category        Models
 * @author          Chris Kacerguis
 * @license         MIT
 * @link            https://github.com/chriskacerguis/ci-crud
 * @version         1.0.0
 */

class CRUD_model extends CI_Model
{

    /**
     * @var string
     */
    protected $table;

    /**
     * @var string
     */
    protected $cols;

    /**
     * @var string
     */
    protected $created;

    /**
     * @var string
     */
    protected $db_key;

    /**
     * constructor
     */
    public function __construct()
    {
        parent::__construct();

        // We need the DB library, so I'll load it here, just in case
        // it hasn't been loaded already.
        $this->load->library('database');

        $this->cols         = $this->db->list_fields($this->table);
        $this->created      = $this->config->item('crud_db_created');
        $this->db_key       = $this->config->item('crud_db_key');
        $this->db_encrypt   = $this->config->item('crud_db_encrypted');

        // Unset the colunms we don't want people to change
        unset($this->cols[$this->config->item('crud_db_key')]);
        unset($this->cols[$this->config->item('crud_db_created')]);
        unset($this->cols[$this->config->item('crud_db_modified')]);

        // If encryption is enabled, then load the encrypt lib
        if ($this->db_encrypt === true) {
            $this->load->library('encrypt');
        }
    }

    /**
     * decrypts a table row, ignoring the columns that aren't encrypted:
     * crud_db_key, crud_db_created, crud_db_modified
     * @param  array  $data [description]
     * @return array  $data     array with decrypted elements
     */
    protected function decrypt_array(array $data)
    {
        foreach ($this->cols as $col) {
            if (isset($data[$col])) {
                $data[$col] = $this->encrypt->deode($data[$col]);
            } else {
                $data[$col] = $data[$col];
            }

        }

        return $data;
    }

    /**
     * set the table for our CRUD model
     * @param  string $table
     * @return [type]
     */
    public function table(string $table)
    {
        $this->table = $table;
        return $this;
    }

    /**
     * creates a record in our table
     * @param  array  $data
     * @return bool
     */
    public function create(array $data)
    {
        $payload = null;

        foreach ($this->cols as $item) {
            if (isset($data[$item])) {
                if ($this->db_encrypt === true) {
                    $payload[$item] = $this->encrypt->encode($data[$item]);
                } else {
                    $payload[$item] = $data[$item];
                }

            }
        }

        if ($payload === null) {
            return false;
        }

        $payload[$this->created] = date('Y-m-d H:i:s');
        return $this->db->insert($this->table, $payload);
    }

    /**
     * returns the record with the given id from our table
     * @param  int    $id
     * @return array
     */
    public function get(string $id = null)
    {
        if ($id === null) {
            $result = $this->db->select()->get($this->table)->result_array();
            if ($this->db_encrypt === true) {
                for ($i = 0; $i <= count($result); $i++) {
                    $result[$i] = $this->decrypt_array($result[$i]);
                }
                return $result;
            }
            return $result;
        }

        $result = $this->db->select()->where($this->db_key, $id)->get($this->table)->row_array();
        if ($this->db_encrypt === true) {
            return $this->decrypt_array($result);
        }
        return $result;
    }

    /**
     * updates the record in the database with the id provided.
     * @param  int    $id
     * @param  array  $data
     * @return bool
     */
    public function update(string $id, array $data)
    {
        $payload = null;

        foreach ($this->cols as $item) {
            if (isset($data[$item])) {
                if ($this->db_encrypt === true) {
                    $payload[$item] = $this->encrypt->encode($data[$item]);
                }
                $payload[$item] = $data[$item];
            }
        }

        if ($payload === null) {
            return false;
        }

        return $this->db->update($this->table, $payload, array($this->db_key => $id));
    }

    /**
     * deleted the reocrd whos id is provided
     * @param  int    $id
     * @return bool
     */
    public function delete(string $id)
    {
        return $this->db->delete($this->table, array($this->db_key => $id));
    }

}

/* End of file crud_model.php */
/* Location: ./application/models/crud_model.php */


text:
#pragma once

#include "../commons.h"
#include "../interrupts/clock.h"
#include "../cpus/cpu_mgmt.h"
#include "process.h"

#include <ds/random.h>
#include <ds/array.h>

void attemp_to_run_scheduler(registers_t* r);
void schedule(registers_t* r);
void enschedule(thread_t* t, cpu_t* cpu);
void enschedule_best(thread_t* t);
void enschedule_to_self(thread_t* t);

void copy_registers(registers_t* r, thread_t* t);
void registers_copy(thread_t* t, registers_t* r);

void initialize_scheduler();

int futex_wait(registers_t* registers, uint32_t* ftx, uint32_t value);
int futex_wake(registers_t* registers, uint32_t* ftx, int num);


text:
'use strict';
const express = require('express');
const router = express.Router();
const { User , Chat, Message } = require('./models');
const { Brigade } = require('../brigade/models');
const { Fire } = require('../fire/models');
const passport = require('passport');
const bcrypt = require('bcryptjs');
const { sendMail,sendEmailAdmins,sendEmailTemplate } = require('../config/emailer');
const { storageAdd } = require('../config/storage');

router.get('/', function (req, res, next) {
  let find = {deletedAt: null};
  if(req.query.name){
    find.name =  { "$regex": req.query.name, "$options": "i" };
  }
  User.find(find,'_id name image location createdAt').limit(10).then(d => { res.json(d);});
});

router.get('/profile/:id/', function (req, res, next) {
  User.findOne({_id: req.params.id, deletedAt: null},'name image bio url updatedAt location createdAt')
  .then(d => {
    Brigade.find({
        members: {$in: [d._id]}
    })
    .then(b=>{
      d.brigades=b;
      Fire.find({
        $or: [
          {fighters: {$in: [d._id]}},
          {users: {$in: [d._id]}}
        ]
      },"title createdAt intensity users fighters").then(f=>{
        let userId=String(d._id).trim();
        let fightes=f.filter(ff=>{
          if(!ff.fighters) return false;
          let found=ff.fighters.find(dd=>{return String(dd).trim()==userId;});
          return found!==undefined;
        });
        let fires=f.filter(ff=>{
          if(!ff.users) return false;
          let findu=ff.users.find(dd=>{ return String(dd).trim()==userId;});
          return findu!==undefined;
        });
        //console.log(d.firesUsers,fires)
        res.json({user:d,fires,fightes});
      }).catch(e=>{
        res.json(d);
      });
    })
    .catch(e=>{
      res.json(d);
    });
  }).catch(e=>{
    res.json(e);
  });
});

router.put('/:id',passport.authenticate('basic', { session: false }), function (req, res, next) {
  User.findOneAndUpdate(req.user._id,req.body,{$new: true, upsert: true}).then(d => { res.json(d);});
});

router.delete('/:id', passport.authenticate('basic', { session: false }),function (req, res, next) {
  User.findOneAndDelete(req.user._id,{},{}).then(d => { res.json(d);});
});

router.post('/login', passport.authenticate('basic',{failWithError: true}), (req, res) => {
  if (req.user) {
    delete req.user.password;
    res.status(200).json( req.user  );
  }else{
    res.status(403).json({  'error': 'No auth'  });
  }
});

router.post('/register', (req, res) => {
  let username;
  if(req.body.username) username= req.body.username.trim();
  else if(req.body.email) username= req.body.email.trim();
  let password = req.body.password.trim();

  bcrypt.genSalt(10, (err, salt) => {
    if (err) {
      return console.log(`error: ${err}`);
    }
    bcrypt.hash(password, salt, (err, hash) => {
        if (err) {
          return console.log(`error: ${err}`);
        }

        let userObj = {
          username: username,
          password: hash,
          name: req.body.name.trim(),
          bio: req.body.bio.trim(),
          city: req.body.city.trim(),
          createdAt: new Date(),
          role: 1
        };

        User.create(userObj, (err, result) => {
          if (err) {
            return res.status(500).json({
              message: 'Internal server error on user.create'+JSON.stringify(err)
            });
          }
          delete result.password;

          sendEmailAdmins("Novo cadastro",JSON.stringify(result));
          sendEmailTemplate(result.username, "user/templates/welcome-email",{user: result});
          res.status(201).json(result);
        });
      });
    });
});

router.post('/update', passport.authenticate('basic', { session: false }), function (req, res, next) {
  User.update({_id: req.user._id},req.body.user)
  .then(d => {  if(d.ok) res.json(req.body.user); else res.sendStatus(500); })
  .catch(e=>{ res.status(500).json(e); });
});

router.post('/image/:id', passport.authenticate('basic', { session: false }),function (req, res, next) {
  var query={_id: req.user._id};
  User.findOne(query).then(r=>{
    req.params.datafolder="user";
    req.params.datafield="image";
    storageAdd(req,res,r,User);
  });
});

router.get('/logout', (req,res)=>{
  req.logout();
  res.json({'success':'ok'});
});

router.post('/pushregister/:type/',passport.authenticate('basic', { session: false }), (req,res)=>{
  var set={};
  if(req.params.type=='android') set={androidkey: req.body.androidkey};
  else set={ioskey: req.body.ioskey};//ios
  User.findOneAndUpdate(req.user._id,{$set: set}).exec(v=>{
    console.log(v);
    res.json({'success':'ok'});
  });
});

router.post('/pushunregister/:type/',passport.authenticate('basic', { session: false }), (req,res)=>{
  var set='';
  if(req.params.type==='android') set={androidkey: null};
  else set={ioskey: null};
  User.findOneAndUpdate(req.user._id,{$set: set}).exec(v=>{
    console.log(v);
    res.json({'success':'ok'});
  });
});

router.get('/recover/:username/', (req, res) => {
  console.log("recover password" + req.params.username);
  User.findOne({username: req.params.username}).then(u=>{
    if(!u) res.sendStatus(404);

    bcrypt.genSalt(10, (err, salt) => {
      if(err)return res.status(500).json( err );
      u.token=salt;
      u.save();
      sendEmailTemplate(u.username, "user/templates/recover-email",{user: u, token: u.token},(err,resp)=>{
        if(err) res.status(500).json(err );
        else res.status(200).json( resp  );
      });
    });

  });
});

router.get('/recovercheck/:key/',(req, res) => {
  User.findOne({token: req.params.key}).then(u=>{
    if(!u) return res.sendStatus(404);
    res.status(200).json( u );
  });
});

router.post('/recoverpass/:key/',(req, res) => {
  User.findOne({token: req.params.key}).then(u=>{
    if(!u) return res.sendStatus(404);

    bcrypt.genSalt(10, (err, salt) => {
      if (err) {
        return res.status(500).json( err );
      }
      bcrypt.hash(req.body.password, salt, (err, hash) => {
          if (err) {
            return res.status(500).json( err );
          }
          u.password=hash;
          u.save();
          res.status(200).json( u );
      });
    });
  });
});

module.exports = router;


text:
/*
 * Copyright (C) 2001, 2002,
 *
 * Hewlett-Packard Arjuna Labs,
 * Newcastle upon Tyne,
 * Tyne and Wear,
 * UK.
 *
 * $Id: OTSThread.java 2342 2006-03-30 13:06:17Z  $
 */

package com.arjuna.ats.jts.thread;

import org.omg.CosTransactions.Control;

import com.arjuna.ats.arjuna.exceptions.FatalError;
import com.arjuna.ats.internal.jts.OTSImpleManager;
import com.arjuna.ats.internal.jts.orbspecific.CurrentImple;
import com.arjuna.ats.jts.logging.jtsLogger;

/**
 * Create an OTS transactional thread. When the thread is created it is
 * automatically registered with the current transaction, and removed
 * when the transaction terminates.
 *
 * @author Mark Little (mark_little@hp.com)
 * @version $Id: OTSThread.java 2342 2006-03-30 13:06:17Z  $
 * @since JTS 1.2.4.
 */

public class OTSThread extends Thread
{

    /*
     * Can't use finalize since it may be called by
     * some other thread than this one.
     */

    public void terminate ()
    {
	try
	{
	    CurrentImple current = OTSImpleManager.current();

	    if (current != null)
	    {
		Control c = current.suspend();

		c = null;
	    }
	}
	catch (Exception e)
	{
	}
    }

    public void run ()
    {
	if (_currentControl != null)
	{
	    try
	    {
		CurrentImple current = OTSImpleManager.current();

		if (current != null)
		{
		    current.resume(_currentControl);
		    current = null;
		}
	    }
	    catch (Exception e)
	    {
            jtsLogger.i18NLogger.warn_thread_resumefailed( "OTSThread.run", e);

		throw new FatalError("OTSThread.run - "+jtsLogger.i18NLogger.get_thread_resumefailederror(), e);
	    }

	    _currentControl = null;
	}
    }

    protected OTSThread ()
    {
	try
	{
	    CurrentImple current = OTSImpleManager.current();

	    if (current != null)
	    {
		_currentControl = current.get_control();
		current = null;
	    }
	}
	catch (Exception e)
	{
	    _currentControl = null;
	}
    }

    private Control _currentControl;

}


text: Sinatra practice - coupon database


text:
<?php

require 'auth.inc';
require 'guiconfig.inc';

array_make_branch($config,'shutdown');
$pconfig['enable'] = isset($config['shutdown']['enable']);
$pconfig['minute'] = $config['shutdown']['minute'];
$pconfig['hour'] = $config['shutdown']['hour'];
$pconfig['day'] = $config['shutdown']['day'];
$pconfig['month'] = $config['shutdown']['month'];
$pconfig['weekday'] = $config['shutdown']['weekday'];
$pconfig['all_mins'] = $config['shutdown']['all_mins'];
$pconfig['all_hours'] = $config['shutdown']['all_hours'];
$pconfig['all_days'] = $config['shutdown']['all_days'];
$pconfig['all_months'] = $config['shutdown']['all_months'];
$pconfig['all_weekdays'] = $config['shutdown']['all_weekdays'];

$a_months = explode(" ",gtext("January February March April May June July August September October November December"));
$a_weekdays = explode(" ",gtext("Sunday Monday Tuesday Wednesday Thursday Friday Saturday"));

if ($_POST){
	unset($input_errors);

	$pconfig = $_POST;

	// Validate synchronization time
	if(isset($_POST['enable'])) {
		do_input_validate_synctime($_POST, $input_errors);
	}

	if (empty($input_errors)) {
		$config['shutdown']['enable'] = isset($_POST['enable']) ? true : false;
		$config['shutdown']['minute'] = !empty($_POST['minute']) ? $_POST['minute'] : null;
		$config['shutdown']['hour'] = !empty($_POST['hour']) ? $_POST['hour'] : null;
		$config['shutdown']['day'] = !empty($_POST['day']) ? $_POST['day'] : null;
		$config['shutdown']['month'] = !empty($_POST['month']) ? $_POST['month'] : null;
		$config['shutdown']['weekday'] = !empty($_POST['weekday']) ? $_POST['weekday'] : null;
		$config['shutdown']['all_mins'] = $_POST['all_mins'];
		$config['shutdown']['all_hours'] = $_POST['all_hours'];
		$config['shutdown']['all_days'] = $_POST['all_days'];
		$config['shutdown']['all_months'] = $_POST['all_months'];
		$config['shutdown']['all_weekdays'] = $_POST['all_weekdays'];

		write_config();

		$retval = 0;
		if (!file_exists($d_sysrebootreqd_path)) {
			config_lock();
			$retval |= rc_update_service("cron");
			config_unlock();
		}

		$savemsg = get_std_save_message($retval);
	}
}
$pgtitle = [gtext('System'),gtext('Shutdown'),gtext('Scheduled')];
?>
<?php include 'fbegin.inc';?>

<?=gtext("Now");?>

<a href="shutdown_sched.php" title="<?=gtext('Reload page');?>"><?=gtext("Scheduled");?>

			<form action="shutdown_sched.php" method="post" name="iform" id="iform" onsubmit="spinner()">
				<?php if (!empty($input_errors)) print_input_errors($input_errors);?>

					<?php html_titleline_checkbox("enable", gtext("Scheduled Shutdown"), !empty($pconfig['enable']) ? true : false, gtext("Enable"), "enable_change(false)");?>

						<?=gtext("Time");?>

									<?=gtext("Minutes");?>
									<?=gtext("Hours");?>
									<?=gtext("Days");?>
									<?=gtext("Months");?>
									<?=gtext("Week Days");?>

										<input type="radio" name="all_mins" id="all_mins1" value="1" <?php if (1 == $pconfig['all_mins']) echo "checked=\"checked\"";?> />
										<?=gtext("All");?>

										<input type="radio" name="all_mins" id="all_mins2" value="0" <?php if (1 != $pconfig['all_mins']) echo "checked=\"checked\"";?> />
										<?=gtext("Selected");?> ..

													<select multiple="multiple" size="12" name="minute[]" id="minutes1" onchange="set_selected('all_mins')">
														<?php for ($i = 0; $i <= 11; $i++):?>
														<option value="<?=$i;?>" <?php if (is_array($pconfig['minute']) && in_array("$i", $pconfig['minute'])) echo "selected";?>><?=htmlspecialchars($i);?></option>
														<?php endfor;?>
													</select>

													<select multiple="multiple" size="12" name="minute[]" id="minutes2" onchange="set_selected('all_mins')">
														<?php for ($i = 12; $i <= 23; $i++):?>
														<option value="<?=$i;?>" <?php if (is_array($pconfig['minute']) && in_array("$i", $pconfig['minute'])) echo "selected";?>><?=htmlspecialchars($i);?></option>
														<?php endfor;?>
													</select>

													<select multiple="multiple" size="12" name="minute[]" id="minutes3" onchange="set_selected('all_mins')">
														<?php for ($i = 24; $i <= 35; $i++):?>
														<option value="<?=$i;?>" <?php if (is_array($pconfig['minute']) && in_array("$i", $pconfig['minute'])) echo "selected";?>><?=htmlspecialchars($i);?></option>
														<?php endfor;?>
													</select>

													<select multiple="multiple" size="12" name="minute[]" id="minutes4" onchange="set_selected('all_mins')">
														<?php for ($i = 36; $i <= 47; $i++):?>
														<option value="<?=$i;?>" <?php if (is_array($pconfig['minute']) && in_array("$i", $pconfig['minute'])) echo "selected";?>><?=htmlspecialchars($i);?></option>
														<?php endfor;?>
													</select>

													<select multiple="multiple" size="12" name="minute[]" id="minutes5" onchange="set_selected('all_mins')">
														<?php for ($i = 48; $i <= 59; $i++):?>
														<option value="<?=$i;?>" <?php if (is_array($pconfig['minute']) && in_array("$i", $pconfig['minute'])) echo "selected";?>><?=htmlspecialchars($i);?></option>
														<?php endfor;?>
													</select>

										<input type="radio" name="all_hours" id="all_hours1" value="1" <?php if (1 == $pconfig['all_hours']) echo "checked=\"checked\"";?> />
										<?=gtext("All");?>

										<input type="radio" name="all_hours" id="all_hours2" value="0" <?php if (1 != $pconfig['all_hours']) echo "checked=\"checked\"";?> />
										<?=gtext("Selected");?> ..

													<select multiple="multiple" size="12" name="hour[]" id="hours1" onchange="set_selected('all_hours')">
														<?php for ($i = 0; $i <= 11; $i++):?>
														<option value="<?=$i;?>" <?php if (is_array($pconfig['hour']) && in_array("$i", $pconfig['hour'])) echo "selected";?>><?=htmlspecialchars($i);?></option>
														<?php endfor;?>
													</select>

													<select multiple="multiple" size="12" name="hour[]" id="hours2" onchange="set_selected('all_hours')">
														<?php for ($i = 12; $i <= 23; $i++):?>
														<option value="<?=$i;?>" <?php if (is_array($pconfig['hour']) && in_array("$i", $pconfig['hour'])) echo "selected";?>><?=htmlspecialchars($i);?></option>
														<?php endfor;?>
													</select>

										<input type="radio" name="all_days" id="all_days1" value="1" <?php if (1 == $pconfig['all_days']) echo "checked=\"checked\"";?> />
										<?=gtext("All");?>

										<input type="radio" name="all_days" id="all_days2" value="0" <?php if (1 != $pconfig['all_days']) echo "checked=\"checked\"";?> />
										<?=gtext("Selected");?> ..

													<select multiple="multiple" size="12" name="day[]" id="days1" onchange="set_selected('all_days')">
														<?php for ($i = 1; $i <= 12; $i++):?>
														<option value="<?=$i;?>" <?php if (is_array($pconfig['day']) && in_array("$i", $pconfig['day'])) echo "selected";?>><?=htmlspecialchars($i);?></option>
														<?php endfor;?>
													</select>

													<select multiple="multiple" size="12" name="day[]" id="days2" onchange="set_selected('all_days')">
														<?php for ($i = 13; $i <= 24; $i++):?>
														<option value="<?=$i;?>" <?php if (is_array($pconfig['day']) && in_array("$i", $pconfig['day'])) echo "selected";?>><?=htmlspecialchars($i);?></option>
														<?php endfor;?>
													</select>

													<select multiple="multiple" size="7" name="day[]" id="days3" onchange="set_selected('all_days')">
														<?php for ($i = 25; $i <= 31; $i++):?>
														<option value="<?=$i;?>" <?php if (is_array($pconfig['day']) && in_array("$i", $pconfig['day'])) echo "selected";?>><?=htmlspecialchars($i);?></option>
														<?php endfor;?>
													</select>

										<input type="radio" name="all_months" id="all_months1" value="1" <?php if (1 == $pconfig['all_months']) echo "checked=\"checked\"";?> />
										<?=gtext("All");?>

										<input type="radio" name="all_months" id="all_months2" value="0" <?php if (1 != $pconfig['all_months']) echo "checked=\"checked\"";?> />
										<?=gtext("Selected");?> ..

													<select multiple="multiple" size="12" name="month[]" id="months" onchange="set_selected('all_months')">
														<?php $i = 1; foreach ($a_months as $month):?>
														<option value="<?=$i;?>" <?php if (isset($pconfig['month']) && in_array("$i", $pconfig['month'])) echo "selected";?>><?=htmlspecialchars($month);?></option>
														<?php $i++; endforeach;?>
													</select>

										<input type="radio" name="all_weekdays" id="all_weekdays1" value="1" <?php if (1 == $pconfig['all_weekdays']) echo "checked=\"checked\"";?> />
										<?=gtext("All");?>

										<input type="radio" name="all_weekdays" id="all_weekdays2" value="0" <?php if (1 != $pconfig['all_weekdays']) echo "checked=\"checked\"";?> />
										<?=gtext("Selected");?> ..

													<select multiple="multiple" size="7" name="weekday[]" id="weekdays" onchange="set_selected('all_weekdays')">
														<?php $i = 0; foreach ($a_weekdays as $day):?>
														<option value="<?=$i;?>" <?php if (isset($pconfig['weekday']) && in_array("$i", $pconfig['weekday'])) echo "selected";?>><?=$day;?></option>
														<?php $i++; endforeach;?>
													</select>

							<?=gtext("Note: Ctrl-click (or command-click on the Mac) to select and de-select minutes, hours, days and months.");?>

					<input name="Submit" type="submit" class="formbtn" value="<?=gtext("Save");?>" onclick="enable_change(true)" />

				<?php include 'formend.inc';?>
			</form>

<?php include 'fend.inc';?>


text:
<?php

namespace Marvel\SecondaryBundle\Controller;

use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\JsonResponse;
use Marvel\CoreBundle\Controller\BaseController;
use Marvel\SecondaryBundle\Manager\SecondaryManager;
use Marvel\CoreBundle\Util\HttpStatusHelper;
use Marvel\CoreBundle\Util\SimpleUpload;

class DefaultController extends BaseController
{

    public function indexAction(){
        return $this->render('MarvelLoginBundle:Page:login.html.twig');
    }

    public function addAction(){
        return $this->render('MarvelSecondaryBundle:Page:secondary-add.html.twig');
    }

    public function addAgentAction(){
    	return $this->render('MarvelSecondaryBundle:Page:agent-add.html.twig');
    }

    public function listAgentAction(){
    	$this->init();

        try {

            $act = new DeveloperManager($this->getDoctrine()->getManager());
            $res['data'] = $act->showAllDeveloper();

            return $this->render('MarvelDeveloperBundle:Page:developer-list.html.twig',$res);

        } catch (\Exception $e) {
            return $this->errorResponse('Post developer failed, Please try again later', HttpStatusHelper::HTTP_PRECONDITION_FAILED);
        }
    	return $this->render('MarvelDeveloperBundle:Page:developer-list.html.twig');
    }

    public function addCompanyAction(){
    	return $this->render('MarvelSecondaryBundle:Page:company-add.html.twig');
    }

    public function postCompanyAction(Request $request){

        $this->init();

    	try {
            $post = $request->request->all();
            $file = $request->files->get('logo');

            $fileName = "";

            if(!is_null($file)){

                /* @var $targetDir \Marvel\CoreBundle */
                $targetDir = $this->container->getParameter('marvel.core.upload_logo_company');

                $upload = new SimpleUpload();
                $upload = $upload->fileUpload($file,$post['company_name'],$targetDir);
                $fileName = $upload;
            }

            $act = new SecondaryManager($this->getDoctrine()->getManager());
            $res = $act->insertCompany($post,$fileName);

            return  $this->successResponse(array('data' => $res));

        } catch (\Exception $e) {
            return $this->errorResponse('Post developer failed, Please try again later', HttpStatusHelper::HTTP_PRECONDITION_FAILED);
        }

    }

    public function listCompanyAction(){
    	$this->init();

        try {

            $act = new SecondaryManager($this->getDoctrine()->getManager());
            $res['data'] = $act->showAllCompany();

            return $this->render('MarvelDeveloperBundle:Page:developer-list.html.twig',$res);

        } catch (\Exception $e) {
            return $this->errorResponse('Post developer failed, Please try again later', HttpStatusHelper::HTTP_PRECONDITION_FAILED);
        }
    	return $this->render('MarvelDeveloperBundle:Page:developer-list.html.twig');
    }
}