text:
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Reactive.Linq;
using System.Text;
using FluentAssertions;
using RichardSzalay.MockHttp;
using Xunit;

namespace TypedRest.Endpoints.Reactive
{
    [Collection("Endpoint")]
    public class StreamingCollectionEndpointTest : EndpointTestBase
    {
        private readonly IStreamingCollectionEndpoint<MockEntity> _endpoint;

        public StreamingCollectionEndpointTest()
        {
            _endpoint = new StreamingCollectionEndpoint<MockEntity>(EntryEndpoint, "endpoint");
        }

        [Fact]
        public void TestGetObservable()
        {
            Mock.Expect(HttpMethod.Get, "http://localhost/endpoint")
                .WithHeaders("Range", "elements=0-")
                .Respond(HttpStatusCode.PartialContent,
                     new StringContent("[{\"id\":5,\"name\":\"test1\"},{\"id\":6,\"name\":\"test2\"}]", Encoding.UTF8, JsonMime)
                     {
                         Headers = {ContentRange = new ContentRangeHeaderValue(from: 0, to: 1) {Unit = "elements"}}
                     });

            Mock.Expect(HttpMethod.Get, "http://localhost/endpoint")
                .WithHeaders("Range", "elements=2-")
                .Respond(HttpStatusCode.PartialContent,
                     new StringContent("[{\"id\":7,\"name\":\"test3\"}]", Encoding.UTF8, JsonMime)
                     {
                         Headers = {ContentRange = new ContentRangeHeaderValue(from: 2, to: 2, length: 3) {Unit = "elements"}}
                     });

            var observable = _endpoint.GetObservable();
            observable.ToEnumerable().ToList().Should().Equal(
                new MockEntity(5, "test1"),
                new MockEntity(6, "test2"),
                new MockEntity(7, "test3"));
        }

        [Fact]
        public void TestGetObservableOffset()
        {
            Mock.Expect(HttpMethod.Get, "http://localhost/endpoint")
                .WithHeaders("Range", "elements=2-")
                .Respond(HttpStatusCode.PartialContent,
                     new StringContent("[{\"id\":7,\"name\":\"test3\"}]", Encoding.UTF8, JsonMime)
                     {
                         Headers = {ContentRange = new ContentRangeHeaderValue(from: 2, to: 2, length: 3) {Unit = "elements"}}
                     });

            var observable = _endpoint.GetObservable(startIndex: 2);
            observable.ToEnumerable().ToList().Should().Equal(new MockEntity(7, "test3"));
        }

        [Fact]
        public void TestGetObservableTail()
        {
            Mock.Expect(HttpMethod.Get, "http://localhost/endpoint")
                .WithHeaders("Range", "elements=-1")
                .Respond(HttpStatusCode.PartialContent,
                     new StringContent("[{\"id\":7,\"name\":\"test3\"}]", Encoding.UTF8, JsonMime)
                     {
                         Headers = {ContentRange = new ContentRangeHeaderValue(from: 2, to: 2, length: 3) {Unit = "elements"}}
                     });

            var observable = _endpoint.GetObservable(startIndex: -1);
            observable.ToEnumerable().ToList().Should().Equal(new MockEntity(7, "test3"));
        }
    }
}


text:
import $ from 'jquery'
import template from './Template.html'
import Mustache from 'mustache'

export default class Intro {

	render(node) {
		$(node).html(
            Mustache.render(template)
        );
    }
}

redpajama_set_name: RedPajamaGithub


text:
<?xml version='1.0' encoding='utf-8'?>
<widget xmlns="http://www.w3.org/ns/widgets" xmlns:cdv="http://cordova.apache.org/ns/1.0"
        id="com.bit6.samples.DemoApp"
        version="0.0.1">
    <name>Bit6 Demo</name>
    <description>
        Fully functional communications app - messaging, voice and video calling between users.
    </description>
    <author email="dev@bit6.com" href="http://bit6.com">
        Bit6 Team
    </author>
    <content src="index.html" />
    <access origin="*" />
    <plugin name="cordova-plugin-whitelist" spec="^1.0.0" />
    <allow-navigation href="*" />
</widget>


text:
@implementation NSDate (ConventKit)

#pragma mark - Class methods

+ (NSDate *)dateFromString:(NSString *)dateStr{
    return [NSDate dateFromString:dateStr format:@"yyyy-MM-dd HH:mm:ss"];
}

+ (NSDate *)dateFromUTCString:(NSString *)dateStr {
    return [NSDate dateFromString:dateStr format:@"yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"];
}

+ (NSDate *)dateFromString:(NSString *)dateStr format:(NSString *)format{
    NSAssert([dateStr length] > 0, @"date string should not empty");
    NSAssert([format length] > 0, @"format parameter should not empty");
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:format];
    return [formatter dateFromString:dateStr];
}

+ (NSDate *)dateFromISO8601String:(NSString *)dateStr {
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    NSLocale *enUSPOSIXLocale = [NSLocale localeWithLocaleIdentifier:@"en_US_POSIX"];
    [dateFormatter setLocale:enUSPOSIXLocale];
    [dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss.SSSSSSZ"];
    NSDate *dt = [dateFormatter dateFromString:dateStr];
    if (dt == nil) {
        [dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ssZ"];
        dt = [dateFormatter dateFromString:dateStr];
    }
    return dt;
}

#pragma mark - Instance methods

- (NSString *)dateToString{
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSString *dateStr = [formatter stringFromDate:self];
    return dateStr;
}

- (NSString *)dateToISO8601String {
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setTimeZone:[NSTimeZone timeZoneWithName:@"UTC"]];
    [formatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss.SSSSSSZZZZZ"];
    NSString *dateStr = [formatter stringFromDate:self];
    return dateStr;
}

- (NSString *)dateToStringWithFormat:(NSString *)format {
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:format];
    NSString *dateStr = [formatter stringFromDate:self];
    return dateStr;
}

- (NSString *)dateToStringWithLocale:(NSString *)localeIdentifier {
    NSLocale *locale = [[NSLocale alloc] initWithLocaleIdentifier:localeIdentifier];
    NSAssert(locale != nil, @"provided localeIdentifier is not a valid locale identifier.");
    NSDateFormatter *formatter = [NSDateFormatter new];
    formatter.dateStyle = NSDateFormatterLongStyle;
    formatter.timeStyle = NSDateFormatterShortStyle;
    formatter.locale = locale;
    NSString *dateStr = [formatter stringFromDate:self];
    return dateStr;
}

- (NSString *)dateToStringWithLocale:(NSString *)localeIdentifier dateStyle:(NSDateFormatterStyle)dateStyle {
    NSLocale *locale = [[NSLocale alloc] initWithLocaleIdentifier:localeIdentifier];
    NSAssert(locale != nil, @"provided localeIdentifier is not a valid locale identifier.");
    NSDateFormatter *formatter = [NSDateFormatter new];
    formatter.dateStyle = dateStyle;
    formatter.locale = locale;
    NSString *dateStr = [formatter stringFromDate:self];
    return dateStr;
}

- (NSInteger)year {
    return [[NSCalendar currentCalendar] component:NSCalendarUnitYear fromDate:self];
}

- (NSInteger)month {
    return [[NSCalendar currentCalendar] component:NSCalendarUnitMonth fromDate:self];
}

- (NSInteger)day {
    return [[NSCalendar currentCalendar] component:NSCalendarUnitDay fromDate:self];
}

- (NSInteger)hour{
    return [[NSCalendar currentCalendar] component:NSCalendarUnitHour fromDate:self];
}

- (NSInteger)minue{
    return [[NSCalendar currentCalendar] component:NSCalendarUnitMinute fromDate:self];
}

- (NSInteger)second{
    return [[NSCalendar currentCalendar] component:NSCalendarUnitSecond fromDate:self];
}

@end


text:
<!DOCTYPE HTML>

<title>CheckedAction (Narayana: narayana-full 5.13.1.Final API)</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="dc.created" content="2022-11-14">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">
<link rel="stylesheet" type="text/css" href="../../../../../jquery/jquery-ui.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Narayana: narayana-full 5.13.1.Final

All Classes

SEARCH:
<input type="text" id="search" value="search" disabled="disabled">
<input type="reset" id="reset" value="reset" disabled="disabled">

JavaScript is disabled on your browser.

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

Package com.arjuna.ats.arjuna.coordinator

Class CheckedAction

java.lang.Object

com.arjuna.ats.arjuna.coordinator.CheckedAction

public class CheckedAction
extends java.lang.Object

If an action attempts to terminate with threads still active we call an
 instance of this class to determine what to do. The default simply prints a
 warning and relies upon the outstanding threads to find out the state of the
 action later. However, this can be overridden, e.g., the thread attempting to
 terminate the action may be made to block. WARNING: watch out for deadlock!

Since:

JTS 1.2.4.

Version:

$Id: CheckedAction.java 2342 2006-03-30 13:06:17Z $

Author:

Mark Little (mark@arjuna.com)

Constructor Summary

Constructors

Constructor
Description

CheckedAction()

Method Summary

All Methods Instance Methods Concrete Methods

Modifier and Type
Method
Description

void
check(boolean isCommit,
     Uid actUid,
     java.util.Hashtable list)

Called during transaction termination if more than one thread is
 associated with the transaction.

Methods inherited from class java.lang.Object

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

Constructor Detail

CheckedAction

public CheckedAction()

Method Detail

check

public void check(boolean isCommit,
                  Uid actUid,
                  java.util.Hashtable list)

Called during transaction termination if more than one thread is
 associated with the transaction. The supplied information should be
 sufficient for application specific implementations to do useful work
 (such as synchronizing on the threads).

 The default implementation simply prints a warning.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Narayana: narayana-full 5.13.1.Final

All Classes

JavaScript is disabled on your browser.

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

Copyright © 2022 JBoss by Red Hat. All rights reserved.


text:
.. _min_cut_segmentation:

Min-Cut Based Segmentation
---------------------------

In this tutorial we will learn how to use the min-cut based segmentation algorithm implemented in the ``pcl::MinCutSegmentation`` class.
This algorithm makes a binary segmentation of the given input cloud. Having objects center and its radius the algorithm divides the cloud on two sets:
foreground and background points (points that belong to the object and those that do not belong).

Theoretical Primer
---------------------------

The idea of this algorithm is as follows:

 #. For the given point cloud algorithm constructs the graph that contains every single point of the cloud as a set of vertices and two more vertices
    called source and sink. Every vertex of the graph that corresponds to the point is connected with source and sink with the edges.
    In addition to these, every vertex (except source and sink) has edges that connect the corresponding point with its nearest neighbours.
 #. Algorithm assigns weights for every edge. There are three different types of weight. Let's examine them:

     * First of all it assigns weight to the edges between clouds points. This weight is called smooth cost and is calculated by the formula:

       .. centered::
          :math:`smoothCost=e^{-(\frac{dist}{ \sigma })^2}`

       Here :math:`dist` is the distance between points. The farther away the points are, the more is probability that the edge will be cut.

     * Next step the algorithm sets data cost. It consists of foreground and background penalties.
       The first one is the weight for those edges that connect clouds points with the source vertex and has the constant user-defined value.
       The second one is assigned to the edges that connect points with the sink vertex and is calculated by the formula:

       .. centered::
          :math:`backgroundPenalty=(\frac{distanceToCenter}{radius})`

       Here :math:`distanceToCenter` is the distance to the expected center of the object in the horizontal plane:

       .. centered::
          :math:`distanceToCenter=\sqrt{(x-centerX)^2+(y-centerY)^2}`

       Radius that occurs in the formula is the input parameter for this algorithm and can be roughly considered as the range from objects center
       outside of which there are no points that belong to foreground (objects horizontal radius).

 #. After all the preparations the search of the minimum cut is made. Based on an analysis of this cut, cloud is divided on foreground and
    background points.

For more comprehensive information please refer to the article
`"Min-Cut Based Segmentation of Point Clouds" <http://gfx.cs.princeton.edu/pubs/Golovinskiy_2009_MBS/index.php>`_.

The code
--------

First of all you will need the point cloud for this tutorial.
`This <https://raw.github.com/PointCloudLibrary/data/master/tutorials/min_cut_segmentation_tutorial.pcd>`_ is a good one for the purposes of the algorithm.
Next what you need to do is to create a file ``min_cut_segmentation.cpp`` in any editor you prefer and copy the following code inside of it:

.. literalinclude:: sources/min_cut_segmentation/min_cut_segmentation.cpp
   :language: cpp
   :linenos:

The explanation
---------------

Now let's study out what is the purpose of this code. First few lines will be omitted, because they are obvious.

.. literalinclude:: sources/min_cut_segmentation/min_cut_segmentation.cpp
   :language: cpp
   :lines: 11-16

These lines are simply loading the cloud from the .pcd file.

.. literalinclude:: sources/min_cut_segmentation/min_cut_segmentation.cpp
   :language: cpp
   :lines: 18-23

This few lines are not necessary. Their only purpose is to show that ``pcl::MinCutSegmentation`` class can work with indices.

.. literalinclude:: sources/min_cut_segmentation/min_cut_segmentation.cpp
   :language: cpp
   :lines: 25-25

Here is the line where the instantiation of the ``pcl::MinCutSegmentation`` class takes place.
It is the tamplate class that has only one parameter - PointT - which says what type of points will be used.

.. literalinclude:: sources/min_cut_segmentation/min_cut_segmentation.cpp
   :language: cpp
   :lines: 26-27

These lines provide the algorithm with the cloud that must be segmented and the indices.

.. literalinclude:: sources/min_cut_segmentation/min_cut_segmentation.cpp
   :language: cpp
   :lines: 29-35

As mentioned before, algorithm requires point that is known to be the objects center. These lines provide it.

.. literalinclude:: sources/min_cut_segmentation/min_cut_segmentation.cpp
   :language: cpp
   :lines: 37-38

These lines set :math:`\sigma` and objects radius required for smooth cost calculation.

.. literalinclude:: sources/min_cut_segmentation/min_cut_segmentation.cpp
   :language: cpp
   :lines: 39-39

This line tells how much neighbours to find when constructing the graph. The more neighbours is set, the more number of edges it will contain.

.. literalinclude:: sources/min_cut_segmentation/min_cut_segmentation.cpp
   :language: cpp
   :lines: 40-40

Here is the line where foreground penalty is set.

.. literalinclude:: sources/min_cut_segmentation/min_cut_segmentation.cpp
   :language: cpp
   :lines: 42-43

These lines are responsible for launching the algorithm. After the segmentation clusters will contain the result.

.. literalinclude:: sources/min_cut_segmentation/min_cut_segmentation.cpp
   :language: cpp
   :lines: 45-45

You can easily access the flow value that was computed during the graph cut. This is exactly what happening here.

.. literalinclude:: sources/min_cut_segmentation/min_cut_segmentation.cpp
   :language: cpp
   :lines: 47-52

These lines simply create the instance of ``CloudViewer`` class for result visualization.

Compiling and running the program
---------------------------------

Add the following lines to your CMakeLists.txt file:

.. literalinclude:: sources/min_cut_segmentation/CMakeLists.txt
   :language: cmake
   :linenos:

After you have made the executable, you can run it. Simply do::

  $ ./min_cut_segmentation

After the segmentation the cloud viewer window will be opened and you will see something similar to those images:

.. image:: images/min_cut_segmentation.jpg
   :height: 360px


text:
package org.mini2Dx.core.di.exception;

/**
 * Thrown when a bean fails to initialise
 */
public class BeanInitialisationException extends BeanException {
	private static final long serialVersionUID = -4525166692000428401L;

	public BeanInitialisationException(String className) {
		super("Could not initialise bean of type " + className + ". No suitable constructor found.");
	}

}


text:
class btDynamicsWorld;

class BulletVehicleRaycaster : public btVehicleRaycaster
{
public:
	BulletVehicleRaycaster(btDynamicsWorld* pWorld);

	void* castRay(const btVector3& from, const btVector3& to, btVehicleRaycasterResult& result) override;

private:
	btDynamicsWorld* m_pDynamicsWorld;
};


text:
var program = require('commander')
var fs = require('../lib/utils/fs-plus2')
var logger = require('../lib/utils/logger')

program
  .version(require('../package.json').version)
  .usage('[command] [options]')
  .description('another static glog generator by using ghost theme')
  .option('-c, --config <path>', 'set config path. default is ./config.yaml')
  .option('-p, --port', 'the port of local server')
  .action(function(cmd, config) {
    setCliConfig()
    console.log(1, global.configFile);
  })

program
  .command('generate')
  .alias('g')
  .description('generate blog')
  .action(function() {
    setCliConfig()
    generate()
  })

program.command('init')
  .alias('i')
  .description('initialize blog folders in current directory')
  .action(function() {
    setCliConfig()
    require('./sg-init')()
  })

program.command('clean')
  .alias('c')
  .description('clean temp dir')
  .action(function() {
    setCliConfig()
    clean()
  })

program.command('deploy')
  .alias('d')
  .description('deploy to server, use config.deploy in config.yaml as command')
  .action(function() {
    setCliConfig()
    deploy()
  })
program.command('generateAndDeploy')
  .alias('gd')
  .description('generate and deploy')
  .action(function() {
    setCliConfig()
    var pool = generate()
    pool.on('finish', deploy)
  })

program.command('server')
  .alias('s')
  .description('start a static server, which would auto generate when posts changed')
  .action(function() {
    setCliConfig()
    server()
  })
program.parse(process.argv);

function setCliConfig() {
  global.cliConfig = program
}

function generate(pool) {
  var config = require('../lib/config')
  var Temp = require('../lib/utils/temp')
  var logger = require('../lib/utils/logger')
  if (!fs.existsSync(config.paths.theme)) {
    logger.logErrorAndExit(new Error('Default theme is not found!!! [' + config.paths.theme + ']'))
  }

  return require('../lib/statical_ghost').generate(pool)
}

function clean() {
  require('../lib/utils/logger').info('clean temp dir...');
  require('../lib/utils/temp').clear()
}

function deploy() {
  logger.info('start deploying...')
  var exec = require('child_process').exec
  var config = require('../lib/config')
  if (!config.deploy) {
    logger.warn('no deploy commands found, plz check yout config file')
    return
  }
  exec(config.deploy, {
    maxBuffer: 200
  }, function(error, stdout, stderr) {
    error && console.error(error)
    console.log(stdout)
    console.error(stderr)
  })
}

function server() {
  var chokidar = require('chokidar');
  var config = require('../lib/config')
  var staticalGhost = require('../lib/statical_ghost')
  var static = require('node-static')
  var pool = require('../lib/thread').pool({
    autoKill: false
  })
  var isBusy = false
  pool.on('finish', function() {
      isBusy = false
      console.log('')
      logger.info('finish generating...')
    })
    // One-liner for current directory, ignores .dotfiles
  var last = new Date().getTime()
  var onFile = function(event, file) {
    if(['add','change','unlink','rename'].indexOf(event)<0){
      return false
    }
    var now = new Date().getTime()
    if (!isBusy && now - last > 3000) {
      isBusy = true
      if (event !== 'change'
          ||file.indexOf(config.paths.themes) >= 0//主题改变则清楚缓存并重新复制
          ||file.indexOf(config.paths.files) >= 0){ // 文件改变
        clean()
      }
      logger.info('start generating...')
      staticalGhost.generate(pool)
      last = new Date().getTime()
    }
  }
  chokidar.watch([config.paths.posts,
      config.paths.theme,
      config.paths.files,
      config.configFile
    ])
    .on('raw', onFile)

  var port = program.port || 8080
  var staticServer = new static.Server(config.paths.public, {
    cache: false,
    headers: {
      'Expires': '-1',
      'Cache-Control': 'no_cache',
      'Pragma': 'no-cache'
    }
  });

  require('http').createServer(function(request, response) {
    request.addListener('end', function() {
      staticServer.serve(request, response);
    }).resume();
  }).listen(port);
  logger.info('start server at: \n\n    http://127.0.0.1:' + port + '\n\n    press Ctrl+C to exit the server')
}

module.exports = program


text:
package com.google.security.zynamics.binnavi.API.disassembly;

import java.util.Date;

// / Used to listen on address projects.
/**
 * Interface that can be implemented by objects that want to be notified about changes in
 * {@link Project} objects.
 */
public interface IProjectListener {
  // ! Signals a new address space in the project.
  /**
   * Invoked after an address space was added to the project.
   *
   * @param project The project where the address space was added.
   * @param addressSpace The address space that was added to the project.
   */
  void addedAddressSpace(Project project, AddressSpace addressSpace);

  // ! Signals a new debugger template in the project.
  /**
   * Invoked after a debugger template was added to the project.
   *
   * @param project The project where the debugger template was added.
   * @param template The debugger template that was added to the project.
   */
  void addedDebuggerTemplate(Project project, DebuggerTemplate template);

  // ! Signals a new project trace.
  /**
   * Invoked after a new trace was added to the project.
   *
   * @param project The project where the new trace was created.
   * @param trace The new trace that was added to the project.
   */
  void addedTrace(Project project, Trace trace);

  // ! Signals a new project view.
  /**
   * Invoked after a view was added to the project.
   *
   * @param project The project where the view was added.
   * @param view The view that was added to the project.
   */
  void addedView(Project project, View view);

  // ! Signals a change in the project description.
  /**
   * Invoked after the description of the project changed.
   *
   * @param project The project whose description changed.
   * @param description The new description value of the project.
   */
  void changedDescription(Project project, String description);

  // ! Signals a change in the project modification date.
  /**
   * Invoked after the modification date of the project changed.
   *
   * @param project The project whose modification date changed.
   * @param date The new modification date of the project.
   */
  void changedModificationDate(Project project, Date date);

  // ! Signals a change in the project name.
  /**
   * Invoked after the name of the project changed.
   *
   * @param project The project whose name changed.
   * @param name The new name of the project.
   */
  void changedName(Project project, String name);

  // ! Signals that the project was closed.
  /**
   * Invoked after a project was closed.
   *
   *  After this function was invoked, using parts of the project which must be loaded before they
   * can be used leads to undefined behavior.
   *
   * @param project The project that was closed.
   */
  void closedProject(Project project);

  // ! Signals that the project is about to be closed.
  /**
   * Invoked right before a project is closed. The listening object has the opportunity to veto the
   * close process if it still needs to work with the project.
   *
   * @param project The project that is about to be closed.
   *
   * @return True, to indicate that the project can be closed. False, to veto the close process.
   */
  boolean closingProject(Project project);

  // ! Signals the deletion of an address space.
  /**
   * Invoked after an address space was deleted from the project.
   *
   *  After this function was invoked, further usage of the deleted address space or objects inside
   * that address space lead to undefined behavior.
   *
   * @param project The project where the address space was deleted.
   * @param addressSpace The address space that was deleted from the project.
   */
  void deletedAddressSpace(Project project, AddressSpace addressSpace);

  // ! Signals the deletion of a project trace.
  /**
   * Invoked after a trace was deleted from the project.
   *
   *  After this function was invoked, further usage of the deleted trace or objects inside that
   * trace lead to undefined behavior.
   *
   * @param project The project where the trace was deleted.
   * @param trace The trace that was deleted from the project.
   */
  void deletedTrace(Project project, Trace trace);

  // ! Signals the deletion of a view.
  /**
   * Invoked after a view was deleted from the project.
   *
   *  After this function was invoked, further usage of the deleted view or objects inside that view
   * lead to undefined behavior.
   *
   * @param project The project where the view was deleted.
   * @param view The view that was deleted from the project.
   */
  void deletedView(Project project, View view);

  // ! Signals that the project was loaded.
  /**
   * Invoked after the project was loaded.
   *
   * @param project The project that was loaded.
   */
  void loadedProject(Project project);

  // ! Signals the removal of a debugger template.
  /**
   * Invoked after a debugger template was deleted from the project.
   *
   * @param project The project where the trace was deleted.
   * @param template The debugger template that was deleted from the project.
   */
  void removedDebuggerTemplate(Project project, DebuggerTemplate template);
}


text: export type SkyAppLinkQueryParams = { [k: string]: any };


text:
using System.IO;
using NUnit.Framework;

namespace Codentia.Common.Compression.Test
{
    /// <summary>
    /// Unit testing framework for ZipEntry class
    /// </summary>
    [TestFixture]
    public class ZipEntryTest
    {
        /// <summary>
        /// _001_s the length of the read fully_ invalid buffer.
        /// </summary>
        [Test]
        public void _001_ReadFully_InvalidBufferLength()
        {
            FileInfo fi = new FileInfo("TestData/SampleBin/Microsoft.ReportViewer.Common.dll");
            Stream s = File.OpenRead("TestData/SampleBin/Microsoft.ReportViewer.Common.dll");

            byte[] b = ZipEntry.ReadFully(s, -1);

            s.Close();
            s.Dispose();

            Assert.That(b.Length, Is.EqualTo(fi.Length));
        }

        /// <summary>
        /// _002_s the read fully_ buffer too small.
        /// </summary>
        [Test]
        public void _002_ReadFully_BufferTooSmall()
        {
            FileInfo fi = new FileInfo("TestData/SampleBin/Microsoft.ReportViewer.Common.dll");
            Stream s = File.OpenRead("TestData/SampleBin/Microsoft.ReportViewer.Common.dll");

            byte[] b = ZipEntry.ReadFully(s, 50);

            s.Close();
            s.Dispose();

            Assert.That(b.Length, Is.EqualTo(fi.Length));
        }

        /// <summary>
        /// _002_s the read fully_ buffer too big.
        /// </summary>
        [Test]
        public void _002_ReadFully_BufferTooBig()
        {
            FileInfo fi = new FileInfo("TestData/SampleBin/Microsoft.ReportViewer.Common.dll");
            Stream s = File.OpenRead("TestData/SampleBin/Microsoft.ReportViewer.Common.dll");

            byte[] b = ZipEntry.ReadFully(s, fi.Length * 2);

            s.Close();
            s.Dispose();

            Assert.That(b.Length, Is.EqualTo(fi.Length));
        }
    }
}


text:
#pragma once

#include "common/Common.h"       // for uint32
#include "common/RawImage.h"     // for RawImage
#include "decoders/RawDecoder.h" // for RawDecoder
#include "io/Buffer.h"           // for Buffer
#include "tiff/TiffIFD.h"        // for TiffRootIFDOwner
#include <cmath>                 // for NAN

namespace rawspeed {

class CameraMetaData;

class MrwDecoder final : public RawDecoder {
  TiffRootIFDOwner rootIFD;

  uint32 raw_width = 0;
  uint32 raw_height = 0;
  Buffer imageData;
  uint32 bpp = 0;
  uint32 packed = 0;
  float wb_coeffs[4] = {NAN, NAN, NAN, NAN};

public:
  explicit MrwDecoder(const Buffer* file);
  RawImage decodeRawInternal() override;
  void checkSupportInternal(const CameraMetaData* meta) override;
  void decodeMetaDataInternal(const CameraMetaData* meta) override;
  static int isMRW(const Buffer* input);

protected:
  int getDecoderVersion() const override { return 0; }
  void parseHeader();
};

} // namespace rawspeed


text:
class QSettings;
class QString;
class QStringList;

class MixedSettings : public QObject
{
	Q_OBJECT

	public:
		explicit MixedSettings(QList<QSettings*> settings);
		~MixedSettings() override;

		QVariant value(const QString &key, const QVariant &defaultValue = QVariant()) const;
		void setValue(const QString &key, const QVariant &value, const QVariant &defaultValue = QVariant());
		void remove(const QString &key);
		QStringList childKeys() const;
		void beginGroup(const QString &prefix);
		void endGroup();
		void sync();

	private:
		QList<QSettings*> m_settings;
};

#endif // MIXED_SETTINGS_H


text:
#ifndef LSHKIT_MATRIX
#define LSHKIT_MATRIX

#include <fstream>
#include <boost/dynamic_bitset.hpp>

/**
 * \file matrix.h
 * \brief Dataset management.  A dataset is maintained as a matrix in memory.
 *
 * LSHKIT is a main memory indexing data structure and doesn't assume any
 * particular file format.  However, the standalone tools come with the LSHKIT
 * package use the following simple binary file format.
 *
 * The file contains N D-dimensional vectors of single precision floating point numbers.
 *
 * In the beginning of the file are three 32-bit unsigned integers: ELEM-SIZE,
 * SIZE, DIM. ELEM-SIZE is the size of the element, and currently the only
 * valid value is 4, which is the size of float.  SIZE is the number of vectors
 * in the file and DIM is the dimension.
 *
 * The rest of the file is SIZE vectors stored consecutively, and the total
 * size is SIZE * DIM * 4 bytes.
 *
 * Such binary files can be accessed using lshkit::Matrix<float>.
 */

namespace lshkit {

/// Matrix
/**
  * An matrix of size (NxD) is used to store an array of N D-dimensional
  * vectors.
  */
template <class T>
class Matrix
{
    int dim, N;
    T *dims;

    void load (const char *);
    void save (const char *);

#ifdef MATRIX_MMAP
    int fd;
#endif
public:
    /// Reset the size of matrix.
    /**
     * @param dim Dimension of each feature vector.
     * @param N Number of feature vectors.
     */
    void reset (int _dim, int _N)
    {
        dim = _dim;
        N = _N;
        if (dims != NULL) delete[] dims;
        dims = new T[dim * N];
    }

    /// Release memory.
    void free (void) {
        dim = N = 0;
        if (dims != NULL) delete[] dims;
        dims = NULL;
    }

    /// Default constructor.
    /** Allocates an empty matrix.  Should invoke reset or load before using it.*/
    Matrix () :dim(0), N(0), dims(NULL) {}

    /// Constructor, same as Matrix() followed immediately by reset().
    Matrix (int _dim, int _N) : dims(NULL) { reset(_dim, _N); }

    /// Destructor.
    ~Matrix () { if (dims != NULL) delete[] dims; }

    /// Access the ith vector.
    const T *operator [] (int i) const {
        return dims + i * dim;
    }

    /// Access the ith vector.
    T *operator [] (int i) {
        return dims + i * dim;
    }

    int getDim () const {return dim; }
    int getSize () const {return N; }

    /// Peek into a file to determine the size and dimension of the dataset.
    /**
     *  @param path File to peek.
     *  @param elem_size Size of the vector element.
     *  @param size Number of vectors in the file.
     *  @param dim Dimension of the vectors.
     *
     *  This function doesn't read the whole matrix into memory, so it is fast.
     */
    static void peek (const std::string &path, int *elem_size, int *size, int *dim);

    void load (const std::string &path);
    void save (const std::string &path);
    void load (std::istream &is);
    void save (std::ostream &os);

#ifdef MATRIX_MMAP
    void map (const std::string &path);
    void unmap ();
#endif

    /// Construct from a file.
    Matrix (const std::string &path): dims(NULL) { load(path); }

    /// An accessor class to be used with LSH index.
    class Accessor
    {
        const Matrix &matrix_;
        boost::dynamic_bitset<> flags_;
    public:
        typedef unsigned Key;
        typedef const float *Value;

        Accessor(const Matrix &matrix)
            : matrix_(matrix), flags_(matrix.getSize()) {}

        void reset () {
            flags_.reset();
        }

        bool mark (unsigned key) {
            if (flags_[key]) return false;
            flags_.set(key);
            return true;
        }

        const float *operator () (unsigned key) {
            return matrix_[key];
        }
    };

    /*
    class View
    {
        const Matrix<T> *ref_;
        int off_, len_;
    public:
        View (const Matrix<T> *ref, int off, int len)
            : ref_(ref), off_(off), len_(len) {}
        const T *operator [] (int i) const { return ref_->operator[](off_ + i); }
        int getDim () const {return ref_->getDim(); }
        int getSize () const {return len_; }
    };

    View getView (int off, int len) const
    {
        return View(this, off, len);
    }

    View getView () const
    {
        return View(this, 0, getSize());
    }
    */
};

typedef Matrix<float> FloatMatrix;

}

#include "matrix-io.h"
#endif


text:
'''Generative adversarial networks with various objectives and penalties.

'''

import math

from cortex.built_ins.networks.fully_connected import FullyConnectedNet
from cortex.plugins import register_plugin, ModelPlugin
import torch
from torch import autograd
import torch.nn.functional as F

from .utils import log_sum_exp, update_decoder_args, update_encoder_args

def raise_measure_error(measure):
    supported_measures = ['GAN', 'JSD', 'X2', 'KL', 'RKL', 'DV', 'H2', 'W1']
    raise NotImplementedError(
        'Measure `{}` not supported. Supported: {}'.format(measure,
                                                           supported_measures))

def get_positive_expectation(p_samples, measure, average=True):
    log_2 = math.log(2.)

    if measure == 'GAN':
        Ep = - F.softplus(-p_samples)
    elif measure == 'JSD':
        Ep = log_2 - F.softplus(- p_samples)
    elif measure == 'X2':
        Ep = p_samples ** 2
    elif measure == 'KL':
        Ep = p_samples + 1.
    elif measure == 'RKL':
        Ep = -torch.exp(-p_samples)
    elif measure == 'DV':
        Ep = p_samples
    elif measure == 'H2':
        Ep = 1. - torch.exp(-p_samples)
    elif measure == 'W1':
        Ep = p_samples
    else:
        raise_measure_error(measure)

    if average:
        return Ep.mean()
    else:
        return Ep

def get_negative_expectation(q_samples, measure, average=True):
    log_2 = math.log(2.)

    if measure == 'GAN':
        Eq = F.softplus(-q_samples) + q_samples
    elif measure == 'JSD':
        Eq = F.softplus(-q_samples) + q_samples - log_2
    elif measure == 'X2':
        Eq = -0.5 * ((torch.sqrt(q_samples ** 2) + 1.) ** 2)
    elif measure == 'KL':
        Eq = torch.exp(q_samples)
    elif measure == 'RKL':
        Eq = q_samples - 1.
    elif measure == 'DV':
        Eq = log_sum_exp(q_samples, 0) - math.log(q_samples.size(0))
    elif measure == 'H2':
        Eq = torch.exp(q_samples) - 1.
    elif measure == 'W1':
        Eq = q_samples
    else:
        raise_measure_error(measure)

    if average:
        return Eq.mean()
    else:
        return Eq

def get_boundary(samples, measure):
    if measure in ('GAN', 'JSD', 'KL', 'RKL', 'H2', 'DV'):
        b = samples ** 2
    elif measure == 'X2':
        b = (samples / 2.) ** 2
    elif measure == 'W':
        b = None
    else:
        raise_measure_error(measure)

    return b.mean()

def get_weight(samples, measure):
    if measure in ('GAN', 'JSD', 'KL', 'RKL', 'DV', 'H2'):
        return samples ** 2
    elif measure == 'X2':
        return (samples / 2.) ** 2
    elif measure == 'W1':
        return None
    else:
        raise_measure_error(measure)

def generator_loss(q_samples, measure, loss_type=None):
    if not loss_type or loss_type == 'minimax':
        return get_negative_expectation(q_samples, measure)
    elif loss_type == 'non-saturating':
        return -get_positive_expectation(q_samples, measure)
    elif loss_type == 'boundary-seek':
        return get_boundary(q_samples, measure)
    else:
        raise NotImplementedError(
            'Generator loss type `{}` not supported. '
            'Supported: [None, non-saturating, boundary-seek]')

class GradientPenalty(ModelPlugin):

    def routine(self, inputs, penalty_type: str='contractive',
                penalty_amount: float=0.5):
        """

        Args:
            penalty_type: Gradient penalty type for the discriminator.
                {contractive}
            penalty_amount: Amount of gradient penalty for the discriminator.

        """
        if penalty_type == 'contractive':
            penalty = self.contractive_penalty(
                self.nets.network, inputs, penalty_amount=penalty_amount)
        else:
            raise NotImplementedError(penalty_type)

        if penalty:
            self.losses.network = penalty
            key = penalty_type + '_' + 'penalty'
            self.results[key] = penalty.item()

    @staticmethod
    def _get_gradient(inp, output):
        gradient = autograd.grad(outputs=output, inputs=inp,
                                 grad_outputs=torch.ones_like(output),
                                 create_graph=True, retain_graph=True,
                                 only_inputs=True, allow_unused=True)[0]
        return gradient

    def contractive_penalty(self, network, input, penalty_amount=0.5):

        if penalty_amount == 0.:
            return

        if not isinstance(input, (list, tuple)):
            input = [input]

        input = [inp.detach() for inp in input]
        input = [inp.requires_grad_() for inp in input]

        with torch.set_grad_enabled(True):
            output = network(*input)
        gradient = self._get_gradient(input, output)
        gradient = gradient.view(gradient.size()[0], -1)
        penalty = (gradient ** 2).sum(1).mean()

        return penalty_amount * penalty

    def interpolate_penalty(self, network, input, penalty_amount=0.5):

        input = input.detach()
        input = input.requires_grad_()

        if len(input) != 2:
            raise ValueError('tuple of 2 inputs required to interpolate')
        inp1, inp2 = input

        try:
            epsilon = network.inputs.e.view(-1, 1, 1, 1)
        except AttributeError:
            raise ValueError('You must initiate a uniform random variable'
                             '`e` to use interpolation')
        mid_in = ((1. - epsilon) * inp1 + epsilon * inp2)
        mid_in.requires_grad_()

        with torch.set_grad_enabled(True):
            mid_out = network(mid_in)
        gradient = self._get_gradient(mid_in, mid_out)
        gradient = gradient.view(gradient.size()[0], -1)
        penalty = ((gradient.norm(2, dim=1) - 1.) ** 2).mean()

        return penalty_amount * penalty

class Discriminator(ModelPlugin):

    def build(self, discriminator_type: str='convnet', discriminator_args={}):
        """

        Args:
            discriminator_type: Discriminator network type.
            discriminator_args: Discriminator network arguments.

        """
        x_shape = self.get_dims('x', 'y', 'c')
        Encoder, discriminator_args = update_encoder_args(
            x_shape, model_type=discriminator_type,
            encoder_args=discriminator_args)
        discriminator = Encoder(x_shape, dim_out=1, **discriminator_args)
        self.nets.discriminator = discriminator

    def routine(self, real, fake, measure: str='GAN'):
        """

        Args:
            measure: GAN measure.
                {GAN, JSD, KL, RKL (reverse KL), X2 (Chi^2), H2 (squared
                Hellinger), DV (Donsker Varahdan KL), W1 (IPM)}

        """

        X_P = real
        X_Q = fake
        E_pos, E_neg, P_samples, Q_samples = self.score(X_P, X_Q, measure)

        difference = E_pos - E_neg
        self.results.update(Scores=dict(Ep=P_samples.mean().item(),
                                        Eq=Q_samples.mean().item()))
        self.results['{} distance'.format(measure)] = difference.item()
        self.losses.discriminator = -difference

    def score(self, X_P, X_Q, measure):
        discriminator = self.nets.discriminator
        P_samples = discriminator(X_P)
        Q_samples = discriminator(X_Q)

        E_pos = get_positive_expectation(P_samples, measure)
        E_neg = get_negative_expectation(Q_samples, measure)

        return E_pos, E_neg, P_samples, Q_samples

    def visualize(self, real, fake, measure=None):
        X_P = real
        X_Q = fake

        E_pos, E_neg, P_samples, Q_samples = self.score(X_P, X_Q, measure)

        self.add_histogram(dict(fake=Q_samples.view(-1).data,
                                real=P_samples.view(-1).data),
                           name='discriminator output')

class SimpleDiscriminator(Discriminator):
    """
    Discriminator for 1d vectors.

    """

    def build(self, dim_in: int=None, discriminator_args=dict(dim_h=[200, 200])):
        """

        Args:
            dim_in (int): Input size
            dim_out (int): Output size
            classifier_args: Extra arguments for building the classifier

        """
        discriminator = FullyConnectedNet(dim_in, dim_out=1,
                                          **discriminator_args)
        self.nets.discriminator = discriminator

class Generator(ModelPlugin):

    def build(self, dim_z=64, generator_type: str='convnet',
              generator_args=dict(output_nonlinearity='tanh')):
        """

        Args:
            generator_noise_type: Type of input noise for the generator.
            dim_z: Input noise dimension for generator.
            generator_type: Generator network type.
            generator_args: Generator network arguments.

        """
        x_shape = self.get_dims('x', 'y', 'c')

        Decoder, generator_args = update_decoder_args(
            x_shape, model_type=generator_type, decoder_args=generator_args)
        generator = Decoder(x_shape, dim_in=dim_z, **generator_args)

        self.nets.generator = generator

    def routine(self, Z, measure: str=None, loss_type: str='non-saturating'):
        """

        Args:
            loss_type: Generator loss type.
                {non-saturating, minimax, boundary-seek}

        """
        discriminator = self.nets.discriminator
        generator = self.nets.generator

        X_Q = generator(Z)
        samples = discriminator(X_Q)

        g_loss = generator_loss(samples, measure, loss_type=loss_type)
        weights = get_weight(samples, measure)

        self.losses.generator = g_loss
        if weights is not None:
            self.results.Weights = weights.mean().item()

    def generate(self, Z):
        return self.nets.generator(Z)

    def visualize(self, Z):
        X_Q = self.generate(Z)
        self.add_image(X_Q, name='generated')

class GAN(ModelPlugin):
    """
        Generative adversarial network.
        A generative adversarial network on images.
    """

    defaults = dict(
        data=dict(batch_size=dict(train=64, test=64),
                  inputs=dict(inputs='images')),
        train=dict(save_on_lowest='losses.gan')
    )

    def __init__(self):
        super().__init__()

        self.discriminator = Discriminator()
        penalty_contract = dict(nets=dict(network='discriminator'))
        self.penalty = GradientPenalty(contract=penalty_contract)
        self.generator = Generator()

    def build(self, noise_type='normal', dim_z=64):
        """

        Args:
            noise_type: Distribution of input noise for generator.

        """
        self.add_noise('Z', dist=noise_type, size=dim_z)
        self.add_noise('E', dist='uniform', size=1)

        self.generator.build()
        self.discriminator.build()

    def train_step(self, generator_updates=1, discriminator_updates=1):
        """

        Args:
            generator_updates: Number of generator updates per step.
            discriminator_updates: Number of discriminator updates per step.

        """

        for _ in range(discriminator_updates):
            self.data.next()
            inputs, Z = self.inputs('inputs', 'Z')
            generated = self.generator.generate(Z)
            self.discriminator.routine(inputs, generated.detach())
            self.optimizer_step()
            self.penalty.train_step()

        for _ in range(generator_updates):
            self.generator.train_step()

    def eval_step(self):
        self.data.next()

        inputs, Z = self.inputs('inputs', 'Z')
        generated = self.generator.generate(Z)
        self.discriminator.routine(inputs, generated)
        self.penalty.routine(auto_input=True)
        self.generator.routine(auto_input=True)

    def visualize(self, images, Z):
        self.add_image(images, name='ground truth')
        generated = self.generator.generate(Z)
        self.discriminator.visualize(images, generated)
        self.generator.visualize(Z)

register_plugin(GAN)


text:
package org.voovan.docker.command.Exec;

import org.voovan.docker.command.Cmd;
import org.voovan.docker.message.exec.ExecCreate;
import org.voovan.docker.network.DockerClientException;
import org.voovan.docker.network.Result;

import java.util.Arrays;

/**
 * 类文字命名
 *
 * @author helyho
 *         <p>
 *         JDocker Framework.
 *         WebSite: https://github.com/helyho/JDocker
 *         Licence: Apache v2 License
 */
public class CmdExecCreate extends Cmd{
    private ExecCreate execCreate;
    private String nameOrId;

    public CmdExecCreate(String nameOrId) {
        super();
        this.nameOrId = nameOrId;
        execCreate = new ExecCreate();
    }

    public CmdExecCreate cmd(String ... cmd){
        execCreate.getCmd().addAll(Arrays.asList(cmd));
        return this;
    }

    public CmdExecCreate env(String ... env){
        execCreate.getCmd().addAll(Arrays.asList(env));
        return this;
    }

    public CmdExecCreate privileged(boolean privileged){
        execCreate.setPrivileged(privileged);
        return this;
    }

    public CmdExecCreate attachStdin(boolean attachStdin){
        execCreate.setAttachStdin(attachStdin);
        return this;
    }

    public CmdExecCreate attachStdout(boolean attachStdout){
        execCreate.setAttachStdout(attachStdout);
        return this;
    }

    public CmdExecCreate attachStderr(boolean attachStderr){
        execCreate.setAttachStderr(attachStderr);
        return this;
    }

    public CmdExecCreate detachKeys(String detachKeys){
        execCreate.setDetachKeys(detachKeys);
        return this;
    }

    public CmdExecCreate tty(boolean tty){
        execCreate.setTty(tty);
        return this;
    }

    public ExecCreate getEntity(){
        return execCreate;
    }

    public static CmdExecCreate newInstance(String nameOrId){
        return new CmdExecCreate(nameOrId);
    }

    @Override
    public String send() throws Exception {
        Result result = getDockerHttpClient().run("POST","/containers/"+nameOrId+"/exec", getParameters(), execCreate);
        if(result!=null && result.getStatus()>=300){
            throw new DockerClientException(result.getMessage());
        }else{
            return result.getMessage();
        }
    }

}


text:
from django.db import migrations

class Migration(migrations.Migration):

    dependencies = [
        ('order', '0017_auto_20200331_1000'),
    ]

    operations = [
        migrations.RenameField(
            model_name='purchaseorder',
            old_name='URL',
            new_name='link',
        ),
    ]


text:
module Pod
  class Command
    class Cache < Command
      class Clean < Cache
        self.summary = 'Remove the cache for pods'

        self.description = <<-DESC
          Remove the cache for a given pod, or clear the cache completely.

          If there is multiple cache for various versions of the requested pod,
          you will be asked which one to clean. Use `--all` to clean them all.

          If you don't give a pod `NAME`, you need to specify the `--all`
          flag (this is to avoid cleaning all the cache by mistake).
        DESC

        self.arguments = [
          CLAide::Argument.new('NAME', false),
        ]

        def self.options
          [[
            '--all', 'Remove all the cached pods without asking'
          ]].concat(super)
        end

        def initialize(argv)
          @pod_name = argv.shift_argument
          @wipe_all = argv.flag?('all')
          super
        end

        def run
          if @pod_name.nil?
            # Note: at that point, @wipe_all is always true (thanks to `validate!`)
            # Remove all
            clear_cache
          else
            # Remove only cache for this pod
            cache_descriptors = @cache.cache_descriptors_per_pod[@pod_name]
            if cache_descriptors.nil?
              UI.notice("No cache for pod named #{@pod_name} found")
            elsif cache_descriptors.count > 1 && !@wipe_all
              # Ask which to remove
              choices = cache_descriptors.map { |c| "#{@pod_name} v#{c[:version]} (#{pod_type(c)})" }
              index = UI.choose_from_array(choices, 'Which pod cache do you want to remove?')
              remove_caches([cache_descriptors[index]])
            else
              # Remove all found cache of this pod
              remove_caches(cache_descriptors)
            end
          end
        end

        def validate!
          super
          if @pod_name.nil? && !@wipe_all
            # Security measure, to avoid removing the pod cache too agressively by mistake
            help! 'You should either specify a pod name or use the --all flag'
          end
        end

        private

        # Removes the specified cache
        #
        # @param [Array<Hash>] cache_descriptors
        #        An array of caches to remove, each specified with the same
        #        hash as cache_descriptors_per_pod especially :spec_file and :slug
        #
        def remove_caches(cache_descriptors)
          cache_descriptors.each do |desc|
            UI.message("Removing spec #{desc[:spec_file]} (v#{desc[:version]})") do
              FileUtils.rm(desc[:spec_file])
            end
            UI.message("Removing cache #{desc[:slug]}") do
              FileUtils.rm_rf(desc[:slug])
            end
          end
        end

        def clear_cache
          UI.message("Removing the whole cache dir #{@cache.root}") do
            FileUtils.rm_rf(@cache.root)
          end
        end
      end
    end
  end
end


text:
module.exports = {

  server: {
    port: process.env.PORT || 8080,
    ip: process.env.IP || '0.0.0.0',
  },

  logFilePath: (process.env.HOME || process.env.USERPROFILE) + '/node-logs.log',

  currentTimeZone: 'Europe/Madrid',

  filmsListDefaultLength: 5
};


text:
/* global window, __PRODUCTION__ */
/* eslint no-console: [2, { allow: ["error"] }] */

import React from 'react'
import ReactDOM from 'react-dom'
import {CONTAINER_ID} from 'src/common/constants/application'
import Root from './Root'

const reactRoot = window.document.getElementById(CONTAINER_ID)
const render = () => {
  ReactDOM.hydrate(<Root />, reactRoot)
}

render()

if (!__PRODUCTION__ && module.hot) {
  module.hot.accept(render)
}

if (__PRODUCTION__) {
  if (!reactRoot.firstChild ||
      !reactRoot.firstChild.attributes ||
      !reactRoot.firstChild.attributes['data-react-checksum']) {
    console.error(
      'Server-side React render was discarded. Make sure that ' +
      'your initial render does not contain any client-side code.'
    )
  }
}


text:
package com.aerotron.aeropredictor.ui.fragments;

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

import com.aerotron.aeropredictor.R;
import com.aerotron.aeropredictor.model.StockItem;
import com.aerotron.aeropredictor.model.data.StockDataCache;

public class StockDetailFragment extends Fragment {

    public StockDetailFragment() {}

    public static StockDetailFragment newInstance(String symbol) {
        StockDetailFragment fragment = new StockDetailFragment();
        Bundle args = new Bundle();
        args.putString(StockDataCache.STOCK_OBJECT, symbol);
        fragment.setArguments(args);
        return fragment;
    }

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

        // fetch the stockItem object from the data cache
        String symbol = getArguments().getString(StockDataCache.STOCK_OBJECT);
        StockItem stockItem = StockDataCache.getStockDataCache().getStock(symbol);

        // populate view elements
        displayStockStats(view, stockItem);

        return view;
    }

    private void displayStockStats(View view, StockItem stockItem) {

        TextView stockName = (TextView) view.findViewById(R.id.stock_name);
        TextView stockPrice = (TextView) view.findViewById(R.id.stock_price);
        TextView stockSymbol = (TextView) view.findViewById(R.id.stock_symbol);
        TextView stockExchange = (TextView) view.findViewById(R.id.stock_exchange);
        TextView stockChange = (TextView) view.findViewById(R.id.stock_change);
        TextView stockChangeInPercent = (TextView) view.findViewById(R.id.stock_change_in_percent);
        TextView stockOpen = (TextView) view.findViewById(R.id.stock_open);
        TextView stockPreviousClose = (TextView) view.findViewById(R.id.stock_previous_close);
        TextView stockDayHi = (TextView) view.findViewById(R.id.stock_day_high);
        TextView stockDayLo = (TextView) view.findViewById(R.id.stock_day_low);
        TextView stockYearHi = (TextView) view.findViewById(R.id.stock_year_high);
        TextView stockYearLo = (TextView) view.findViewById(R.id.stock_year_low);
        TextView stockCapitalisation = (TextView) view.findViewById(R.id.stock_capitalisation);
        //TextView StockVolume = (TextView) view.findViewById(R.id.stock_volume);
        //TextView StockAverageVolume = (TextView) view.findViewById(R.id.stock_average_volume);
        //TextView StockAnnualYield = (TextView) view.findViewById(R.id.stock_annual_yield);
        //TextView StockAnnualPercentageYield = (TextView) view.findViewById(R.id.stock_annual_percentage_yield);
        TextView stockEarningsPerShare = (TextView) view.findViewById(R.id.stock_earnings_per_share);

        // determine currency
        String currencySymbol;
        String currency = stockItem.getCurrency();

        switch (currency) {
            case "EUR":
                currencySymbol = "€";
                break;
            case "USD":
                currencySymbol = "$";
                break;
            default:
                currencySymbol = "£";
        }

        String changeSymbol;
        if (stockItem.getPrice() > stockItem.getPreviousClose()) {
            changeSymbol = "+";
            stockChange.setTextColor(ContextCompat.getColor(getActivity(), android.R.color.holo_green_light));
            //mStockChange.setCompoundDrawablesWithIntrinsicBounds(R.drawable.ic_arrow_drop_up_green_18dp, 0, 0, 0);
            stockChangeInPercent.setTextColor(ContextCompat.getColor(getActivity(), android.R.color.holo_green_light));
        }
        else if (stockItem.getPrice() < stockItem.getPreviousClose()) {
            changeSymbol = "";
            stockChange.setTextColor(ContextCompat.getColor(getActivity(), android.R.color.holo_red_light));
            //mStockChange.setCompoundDrawablesWithIntrinsicBounds(R.drawable.ic_arrow_drop_down_red_18dp, 0, 0, 0);
            stockChangeInPercent.setTextColor(ContextCompat.getColor(getActivity(), android.R.color.holo_red_light));
        }
        else {
            changeSymbol = "";
            stockChange.setPadding(18, 0, 0, 0);
        }

        stockName.setText(stockItem.getName());
        stockPrice.setText(String.format("%s%.2f", currencySymbol, stockItem.getPrice()));
        stockSymbol.setText(String.format("[%s]", stockItem.getSymbol()));
        stockExchange.setText(stockItem.getStockExchange());
        stockChange.setText(String.format("%s%.2f", changeSymbol, stockItem.getChange()));
        stockChangeInPercent.setText(String.format("%s%.2f", changeSymbol, stockItem.getChangeInPercent()));
        stockOpen.setText(String.format("%s%.2f", currencySymbol, stockItem.getOpen()));
        stockPreviousClose.setText(String.format("%s%.2f", currencySymbol, stockItem.getPreviousClose()));
        stockDayHi.setText(String.format("%s%.2f", currencySymbol, stockItem.getDayHigh()));
        stockDayLo.setText(String.format("%s%.2f", currencySymbol, stockItem.getDayLow()));
        stockYearHi.setText(String.format("%s%.2f", currencySymbol, stockItem.getYearHigh()));
        stockYearLo.setText(String.format("%s%.2f", currencySymbol, stockItem.getYearLow()));
        stockCapitalisation.setText(String.format("%s%s", currencySymbol, String.format("%,.0fM", stockItem.getMarketCapitalisation()/1000000.0)));
        //StockVolume.setText(String.valueOf(stockItem.getVolume()));
        //StockAverageVolume.setText(String.valueOf(stockItem.getAvgVolume()));
        //StockAnnualYield.setText(String.valueOf(stockItem.getAnnualYield()));
        //StockAnnualPercentageYield.setText(String.valueOf(stockItem.getAnnualYieldPercentage()));
        stockEarningsPerShare.setText(String.valueOf(stockItem.getEarningsPerShare()));

    }

}


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package org.kie.grid.impl.base;

import java.util.List;
import org.kie.grid.spi.Service;

/**
 *
 * @author salaboy
 */
public class BaseServiceImpl extends BaseAgentImpl implements Service {

    @Override
    public List<Service> getServices() {
        return null;
    }

}


text:
package org.dbasu.robomvvm.componentadapter.edittext;

import android.text.Editable;
import android.text.TextWatcher;
import android.widget.EditText;

import org.dbasu.robomvvm.componentadapter.textview.TextViewAdapter;

/**
 * Text view adapter to adapt an EditText.
 */
public class EditTextViewAdapter extends TextViewAdapter {

    /**
     * Return the text of the edit text.
     * @return
     *              The text of the edit text.
     */
    public String getText() {
        EditText editText = (EditText) targetObject;
        return editText.getText().toString();
    }

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

        final EditText editText = (EditText) targetObject;

        editText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                raiseEvent(new TextChangeEventArg(EditTextViewAdapter.this, s, start, before, count));
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              xmlns:app="http://schemas.android.com/apk/res-auto"
              xmlns:card_view="http://schemas.android.com/tools"
              android:layout_width="match_parent"
              android:layout_height="match_parent"
              android:clickable="true"
              android:orientation="vertical">

    <android.support.v7.widget.CardView
        android:id="@+id/cardview_questionItem_mainFooter"
        android:layout_width="match_parent"
        android:layout_height="@dimen/widget_dimen_large"
        android:layout_marginBottom="@dimen/view_dimen_small"
        android:layout_marginEnd="@dimen/view_dimen_large"
        android:layout_marginStart="@dimen/view_dimen_large"
        android:layout_marginTop="@dimen/view_dimen_small"
        android:minHeight="@dimen/widget_dimen_large"
        android:padding="@dimen/view_dimen_large"
        app:cardBackgroundColor="@color/colorPrimary_50_per"
        app:cardCornerRadius="@dimen/view_dimen_X_small"
        card_view:cardPreventCornerOverlap="false">

        <ImageView
            android:id="@+id/icon_questionItem_tick"
            android:layout_width="@dimen/view_dimen_X_large"
            android:layout_height="@dimen/view_dimen_X_large"
            android:layout_gravity="center"
            android:src="@mipmap/ic_add_white_36dp"
            />

    </android.support.v7.widget.CardView>

</LinearLayout>


text:
@protocol SimpleTwitterDelegate <NSObject>

#pragma mark - Required

// The delegate "should" be an instance of UIViewController, or a delegate thereto.
// This allows us to display login view controllers in the delegate's frame
@required
- (UIViewController*)targetViewController;

#pragma mark - Optional

// Option callbacks informing delegate of Twitter state
@optional
- (void)simpleTwitterDidLogin:(id)sender;
- (void)simpleTwitterDidFail:(id)sender withHeaders:(NSDictionary*)headers;
- (void)simpleTwitterDidPost:(id)sender;
- (void)simpleTwitterDidCancel:(id)sender;

@end

#pragma mark - Class Interface

@interface SimpleTwitter : SimplySocial <NSURLConnectionDelegate>

#pragma mark - Properties

@property (nonatomic, SIMPLE_WEAK) id <SimpleTwitterDelegate> delegate;
@property (nonatomic, assign) BOOL cacheToken;
@property (nonatomic, assign) BOOL optimize;

#pragma mark - Constructors

// Constructors
- (id)init;
- (id)initWithAPIKey:(NSString*)apiKey andSecret:(NSString*)secret andCallbackURL:(NSString*)callbackURL;

#pragma mark - Twitter Interface

// Twitter Interface
- (void)postText:(NSString*)text;
- (void)postText:(NSString*)text withImage:(UIImage*)image;
- (void)postText:(NSString*)text withURL:(NSString*)url;
- (void)postText:(NSString*)text withImage:(UIImage*)image andURL:(NSString*)url;

#pragma mark - Terminate Session

// Terminate Session
- (void)cancel;

@end


text:
<?php

namespace Jumph\Bundle\ClientBundle\Form\Filter;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;

class EmployeeFilterType extends AbstractType
{
    /**
     * {@inheritdoc}
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->setMethod('GET')
            ->add('name', 'employee_filter_name');
    }

    /**
     * {@inheritdoc}
     */
    public function getName()
    {
        return 'jumph_employee_filter';
    }

    /**
     * {@inheritdoc}
     */
    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(array(
            'csrf_protection'   => false,
            'validation_groups' => array('filtering')
        ));
    }
}


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

<TITLE>
org.openqa.selenium.htmlunit
</TITLE>

<META NAME="date" CONTENT="2011-06-20">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../stylesheet.css" TITLE="Style">

org.openqa.selenium.htmlunit

Interfaces

HtmlUnitDriver.JavaScriptResultsCollection

Classes

HtmlUnitDriver

HtmlUnitKeyboard

HtmlUnitMouse

HtmlUnitWebElement

InputKeysContainer

KeyboardModifiersState


text:
Sample code for LivingTheArchitecture.com

Code samples provided under the MIT license.

Web examples contain code licensed seperately, please refer to the individual projects for their appropriate licensing.