text:
import joblib
import numpy as np
from pylearn2.train_extensions import TrainExtension
from pylearn2.train_extensions.best_params import MonitorBasedSaveBest

class MonitorKeepModelEveryEpoch(TrainExtension):
    def __init__(self, save_prefix, save_freq=1):
        self.save_prefix = save_prefix
        self.save_freq = save_freq
        self.i = 1

    def on_monitor(self, model, dataset, algorithm):
        if self.i % self.save_freq == 0:
            save_path = "{0}_{1:04d}.joblib".format(self.save_prefix, self.i)
            joblib.dump(model, save_path)
        self.i += 1

class EpochBasedScheduledNoiseController(TrainExtension):
    """
    Increases or decreases the level of noise in the training data
    after each fixed number of epochs.  The current implementation
    is a hack just to move things along.

    Ultimately the knowledge of the noise-adding protocol (here,
    a fraction of the sentence to permute) should be decoupled
    from the schedule.  The Dataset chould, for instance, have a method
    that returns an object that knows how to change the kind or level
    of noise that is added to the training data.  This TrainExtension
    would then only need to get that object and call a method to make
    it change the noise-adding protocol.
    """
    def __init__(self, num_epochs):
        self.__dict__.update(locals())
        del self.self
        self.i = 1

    def on_monitor(self, model, dataset, algorithm):
        if self.i % self.num_epochs == 0:
            next_fraction = dataset.get_next_fraction()
            dataset.set_fraction(next_fraction)
        self.i += 1

class SaveWeightsWithinEpoch(object):
    """
    Saves the weights of model parameters at specified intervals.

    Include an instance of this class in the list passed to the
    update_callbacks argument of the SGD class.
    """
    def __init__(self, save_prefix, param_name, save_freq=1):
        self.__dict__.update(locals())
        self.i = 1

    def __call__(self, sgd):
        if self.i % self.save_freq == 0:
            save_path = "{0}_{1:04d}.npy".format(self.save_prefix, self.i)
            names = [x.name for x in sgd.params]
            i = names.index(self.param_name)
            np.save(save_path, sgd.params[i].get_value())
        self.i += 1

class SaveBestAfterKEpochs(MonitorBasedSaveBest):
    """
    It seems that TrainExtension, from which MonitorBasedSaveBest,
    is a new-style class, so I'd expect to be able to call super
    from this subclass.  I had a bit of trouble getting that to work
    so I'm invoking the superclass methods in an old-style way here.
    """
    def __init__(self, k, channel_name, save_path):
        MonitorBasedSaveBest.__init__(self, channel_name, save_path)
        self.k = k
        self.epoch = 0

    def on_monitor(self, model, dataset, algorithm):
        if self.epoch > self.k:
            return MonitorBasedSaveBest.on_monitor(self, model, dataset, algorithm)
        self.epoch += 1

class CurriculumDatasetEpochController(TrainExtension):
    def __init__(self, dataset, epochs):
        """
        """
        self.__dict__.update(locals())
        del self.self
        self.countdown = self.epochs

    def on_monitor(self, model, dataset, algorithm):
        """
        """
        self.countdown = self.countdown - 1

        #print('countdown', self.countdown)

        if self.countdown == 0:
            # Reduce the fraction of permutation by 10%.  This assumes we
            # are starting with a high fraction of permutation and working
            # down from there.
            fraction = self.dataset.fraction
            #print('changing permutation fraction', fraction, fraction * 0.9)
            fraction *= 0.9
            self.dataset.set_fraction(fraction)
            self.countdown == self.epochs

redpajama_set_name: RedPajamaGithub


text:
Converts certain units. CS294 Module 17
Need to give main.py a number to run.


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;

namespace Microsoft.Rest.Generator.Cli
{
    /// <summary>
    /// Helper class for dynamically generating CLI help from Settings.
    /// </summary>
    public static class HelpGenerator
    {
        private static readonly List<HelpExample> Examples = new List<HelpExample>
        {
            new HelpExample
            {
                Description = "Generate C# client in MyNamespace from swagger.json input:",
                Example = "AutoRest.exe -Namespace MyNamespace -Input swagger.json"
            },
            new HelpExample
            {
                Description =
                    "Generate C# client in MyNamespace including custom header from swagger.json input:",
                Example =
                    "AutoRest.exe -Namespace MyNamespace -Header \"Copyright Contoso Ltd\" -Input swagger.json",
            },
            new HelpExample
            {
                Description = "Generate C# client with a credentials property in MyNamespace from swagger.json input:",
                Example =
                    "AutoRest.exe -AddCredentials true -Namespace MyNamespace -CodeGenerator CSharp -Modeler Swagger -Input swagger.json"
            }
        };

        /// <summary>
        /// Generates help string based on the passed in template.
        /// <para>
        /// The following keywords are supported:
        ///   $version$ - version of AutoRest Core
        ///   $syntax$ - replaced with the usage syntax
        ///   $parameters-start$...$parameters-end$ - contains a template for a parameters
        ///   $parameter$ - parameter name
        ///   $parameter-desc$ - parameter documentation
        ///   $examples-start$...$examples-end$ - contains a template for an example
        ///   $example-desc$ - example description
        ///   $example$ - example code
        /// </para>
        /// </summary>
        /// <example>
        ///    Microsoft (R) AutoRest Core $version$
        ///    Copyright (C) Microsoft Corporation. All rights reserved.
        ///
        ///    Syntax         : $syntax$
        ///
        ///    Parameters     :
        ///    $parameters-start$
        ///    -$parameter$ : $parameter-desc$
        ///    $parameters-end$
        ///
        ///    Examples       :
        ///
        ///    $examples-start$
        ///    $example-desc$
        ///    >$example$
        ///    $examples-end$
        /// </example>
        /// <param name="template">Template to use.</param>
        /// <returns>Generated help.</returns>
        public static string Generate(string template)
        {
            if (String.IsNullOrEmpty(template))
            {
                throw new ArgumentNullException("template");
            }

            // Reflect over properties in Settings to get documentation content
            var parameters = new List<Tuple<string, SettingsInfoAttribute>>();
            foreach (PropertyInfo property in typeof(Settings).GetProperties())
            {
                var doc = (SettingsInfoAttribute)property.GetCustomAttributes(
                    typeof(SettingsInfoAttribute)).FirstOrDefault();

                if (doc != null)
                {
                    parameters.Add(new Tuple<string, SettingsInfoAttribute>(property.Name, doc));
                }
            }

            // Generate usage syntax
            var syntaxSection = new StringBuilder("AutoRest.exe ");
            foreach (var parameter in parameters.OrderByDescending(t => t.Item2.IsRequired))
            {
                if (parameter.Item2.IsRequired)
                {
                    syntaxSection.AppendFormat("-{0} <value> ", parameter.Item1);
                }
                else
                {
                    syntaxSection.AppendFormat("[-{0} <value>] ", parameter.Item1);
                }
            }

            // Generate parameters section
            var parametersSection = new StringBuilder();
            const string parametersPattern = @"\$parameters-start\$\r\n(.+)\r\n\$parameters-end\$";
            var parameterTemplate = Regex.Match(template, parametersPattern, RegexOptions.Singleline).Groups[1].Value;
            foreach (PropertyInfo property in typeof(Settings).GetProperties())
            {
                SettingsInfoAttribute doc = (SettingsInfoAttribute)property.GetCustomAttributes(
                    typeof(SettingsInfoAttribute)).FirstOrDefault();

                if (doc != null)
                {
                    parametersSection.AppendLine(parameterTemplate.
                        Replace("$parameter$", property.Name).
                        Replace("$parameter-desc$", doc.Documentation));
                }
            }

            // Generate examples section.
            var examplesSection = new StringBuilder();
            const string examplesPattern = @"\$examples-start\$\r\n(.+)\r\n\$examples-end\$";
            var exampleTemplate = Regex.Match(template, examplesPattern, RegexOptions.Singleline).Groups[1].Value;
            foreach (HelpExample example in Examples)
            {
                examplesSection.AppendLine(exampleTemplate.
                    Replace("$example$", example.Example).
                    Replace("$example-desc$", example.Description));
            }

            // Process template replacing all major sections.
            template = template.
                Replace("$version$", AutoRest.Version).
                Replace("$syntax$", syntaxSection.ToString());

            template = Regex.Replace(template, parametersPattern, parametersSection.ToString(), RegexOptions.Singleline);
            template = Regex.Replace(template, examplesPattern, examplesSection.ToString(), RegexOptions.Singleline);

            return template;
        }
    }
}


text:
package com.fteams.siftrain.util;

import java.util.Random;

public class Tips {
    public static final String [] tips = {
            "Do you feel you're having ease when clearing songs? Try increasing the Overall Difficulty in the Settings > Timing settings.",
            "The game feels slow? Try increasing the Approach Rate in the Settings > Timing settings.",
            "Did you know that you can load new beatmaps without having to restart the game? Go into Settings > Other > Reload Beatmaps!",
            "Can't quite get the beat of the song? Try enabling hint sounds in Settings > Volume settings.",
            "Do you feel the timing window is too small? Try decreasing the Overall Difficulty in the Settings > Timing settings.",
            "If you can't react fast enough to tap on time, try decreasing the Approach Rate in the Settings > Timing settings.",
            "If the notes slow down and speed up, teleport, or stutter, try changing the Sync mode in Settings > Timing settings.",
            "Did you know that you can sort the song list in the song selection screen? Check Settings > Other. ",
            "Did you know that you can play a small fragment of the song in the A-B Repeat mode?\nWarning: There may be sound sync problems, try different timestamps until something sticks!",
            "Did you know that you can change the speed of a song to practice it in slo-mo? Try the changing the playback rate option after selecting a song.\nNote: Due to library limitations, music playback rate can't be changed so these attempts will have no music.",
            "Did you notice there's no ads in this app?",
            "If you've enjoyed using this app, why not rate it on Google Play?"
    };

    public static String getRandomTip()
    {
        Random random = new Random(System.nanoTime());
        return "Tip: " + tips[Math.abs(random.nextInt())%tips.length];
    }
}


text:
#import <math.h>
#import "ccConfig.h"

#import <Foundation/Foundation.h>
#import <Availability.h>

/**
 @file
 cocos2d helper macros
 */

#ifdef __IPHONE_OS_VERSION_MAX_ALLOWED
#define __CC_PLATFORM_IOS 1
#elif defined(__MAC_OS_X_VERSION_MAX_ALLOWED)
#define __CC_PLATFORM_MAC 1
#endif

/*
 * if COCOS2D_DEBUG is not defined, or if it is 0 then
 *	all CCLOGXXX macros will be disabled
 *
 * if COCOS2D_DEBUG==1 then:
 *		CCLOG() will be enabled
 *		CCLOGERROR() will be enabled
 *		CCLOGINFO()	will be disabled
 *
 * if COCOS2D_DEBUG==2 or higher then:
 *		CCLOG() will be enabled
 *		CCLOGERROR() will be enabled
 *		CCLOGINFO()	will be enabled
 */

#define __CCLOGWITHFUNCTION(s, ...) \
NSLog(@"%s : %@",__FUNCTION__,[NSString stringWithFormat:(s), ##__VA_ARGS__])

#if !defined(COCOS2D_DEBUG) || COCOS2D_DEBUG == 0
#define CCLOG(...) do {} while (0)
#define CCLOGINFO(...) do {} while (0)
#define CCLOGERROR(...) do {} while (0)

#elif COCOS2D_DEBUG == 1
#define CCLOG(...) __CCLOGWITHFUNCTION(__VA_ARGS__)
#define CCLOGERROR(...) __CCLOGWITHFUNCTION(__VA_ARGS__)
#define CCLOGINFO(...) do {} while (0)

#elif COCOS2D_DEBUG > 1
#define CCLOG(...) __CCLOGWITHFUNCTION(__VA_ARGS__)
#define CCLOGERROR(...) __CCLOGWITHFUNCTION(__VA_ARGS__)
#define CCLOGINFO(...) __CCLOGWITHFUNCTION(__VA_ARGS__)
#endif // COCOS2D_DEBUG

/** @def CC_SWAP
simple macro that swaps 2 variables
*/
#define CC_SWAP( x, y )			\
({ __typeof__(x) temp  = (x);		\
		x = y; y = temp;		\
})

/** @def CCRANDOM_MINUS1_1
 returns a random float between -1 and 1
 */
#define CCRANDOM_MINUS1_1() ((random() / (float)0x3fffffff )-1.0f)

/** @def CCRANDOM_0_1
 returns a random float between 0 and 1
 */
#define CCRANDOM_0_1() ((random() / (float)0x7fffffff ))

/** @def CC_DEGREES_TO_RADIANS
 converts degrees to radians
 */
#define CC_DEGREES_TO_RADIANS(__ANGLE__) ((__ANGLE__) * 0.01745329252f) // PI / 180

/** @def CC_RADIANS_TO_DEGREES
 converts radians to degrees
 */
#define CC_RADIANS_TO_DEGREES(__ANGLE__) ((__ANGLE__) * 57.29577951f) // PI * 180

#define kCCRepeatForever UINT_MAX -1
/** @def CC_BLEND_SRC
default gl blend src function. Compatible with premultiplied alpha images.
*/
#define CC_BLEND_SRC GL_ONE
#define CC_BLEND_DST GL_ONE_MINUS_SRC_ALPHA

/** @def CC_DIRECTOR_INIT
	- Initializes an CCGLView with 0-bit depth format, and RGB565 render buffer.
	- The CCGLView view will have multiple touches disabled.
	- It will create a UIWindow and it will assign it the 'window_' ivar. 'window_' must be declared before calling this marcro.
    - It will create a UINavigationController and it will assign it the 'navigationController_' ivar. 'navController_' must be declared before using this macro.
    - The director_ will be the root view controller of the navController.
	- It will connect the CCGLView to the Director
	- It will connect the UINavController view to the UIWindow.
	- It will try to run at 60 FPS.
	- It will connect the director with the CCGLView.

 IMPORTANT: If you want to use another type of render buffer (eg: RGBA8)
 or if you want to use a 16-bit or 24-bit depth buffer, you should NOT
 use this macro. Instead, you should create the CCGLView manually.

 @since v0.99.4
 */

#ifdef __CC_PLATFORM_IOS

#define CC_DIRECTOR_INIT()																		\
do	{																							\
	window_ = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];					\
	director_ = (CCDirectorIOS*)[CCDirector sharedDirector];									\
	[director_ setDisplayStats:NO];																\
	[director_ setAnimationInterval:1.0/60];													\
	CCGLView *__glView = [CCGLView viewWithFrame:[window_ bounds]								\
									pixelFormat:kEAGLColorFormatRGB565							\
									depthFormat:0 /* GL_DEPTH_COMPONENT24_OES */				\
							 preserveBackbuffer:NO												\
									 sharegroup:nil												\
								  multiSampling:NO												\
								numberOfSamples:0												\
													];											\
	[director_ setView:__glView];																\
	[director_ setDelegate:self];																\
	director_.wantsFullScreenLayout = YES;														\
	if( ! [director_ enableRetinaDisplay:YES] )													\
		CCLOG(@"Retina Display Not supported");													\
	navController_ = [[UINavigationController alloc] initWithRootViewController:director_];		\
	navController_.navigationBarHidden = YES;													\
	[window_ addSubview:navController_.view];													\
	[window_ makeKeyAndVisible];																\
} while(0)

#elif __CC_PLATFORM_MAC

#define CC_DIRECTOR_INIT(__WINSIZE__)															\
do	{																							\
	NSRect frameRect = NSMakeRect(0, 0, (__WINSIZE__).width, (__WINSIZE__).height);				\
	window_ = [[CCWindow alloc] initWithFrame:frameRect fullscreen:NO];						\
	glView_ = [[CCGLView alloc] initWithFrame:frameRect shareContext:nil];						\
	[self.window setContentView:self.glView];													\
	director_ = (CCDirectorMac*) [CCDirector sharedDirector];									\
	[director_ setDisplayStats:NO];																\
	[director_ setView:self.glView];															\
	[director_ setOriginalWinSize:__WINSIZE__];													\
	[self.window makeMainWindow];																\
	[self.window makeKeyAndOrderFront:self];													\
	[self.window center];																		\
} while(0)

#endif

/** @def CC_NODE_DRAW_SETUP
 Helpful macro that setups the GL server state, the correct GL program and sets the Model View Projection matrix
 @since v2.0
 */
#define CC_NODE_DRAW_SETUP()																	\
do {																							\
	ccGLEnable( glServerState_ );																\
    NSAssert(shaderProgram_, @"No shader program set for node: %@", self);                      \
	[shaderProgram_ use];																		\
	[shaderProgram_ setUniformForModelViewProjectionMatrix];									\
} while(0)

 /** @def CC_DIRECTOR_END
  Stops and removes the director from memory.
  Removes the CCGLView from its parent

  @since v0.99.4
  */
#define CC_DIRECTOR_END()										\
do {															\
	CCDirector *__director = [CCDirector sharedDirector];		\
	[__director end];											\
} while(0)

#if __CC_PLATFORM_IOS

/****************************/
/** RETINA DISPLAY ENABLED **/
/****************************/

/** @def CC_CONTENT_SCALE_FACTOR
 On Mac it returns 1;
 On iPhone it returns 2 if RetinaDisplay is On. Otherwise it returns 1
 */
extern float __ccContentScaleFactor;
#define CC_CONTENT_SCALE_FACTOR() __ccContentScaleFactor

/** @def CC_RECT_PIXELS_TO_POINTS
 Converts a rect in pixels to points
 */
#define CC_RECT_PIXELS_TO_POINTS(__rect_in_pixels__)																		\
	CGRectMake( (__rect_in_pixels__).origin.x / CC_CONTENT_SCALE_FACTOR(), (__rect_in_pixels__).origin.y / CC_CONTENT_SCALE_FACTOR(),	\
			(__rect_in_pixels__).size.width / CC_CONTENT_SCALE_FACTOR(), (__rect_in_pixels__).size.height / CC_CONTENT_SCALE_FACTOR() )

/** @def CC_RECT_POINTS_TO_PIXELS
 Converts a rect in points to pixels
 */
#define CC_RECT_POINTS_TO_PIXELS(__rect_in_points_points__)																		\
	CGRectMake( (__rect_in_points_points__).origin.x * CC_CONTENT_SCALE_FACTOR(), (__rect_in_points_points__).origin.y * CC_CONTENT_SCALE_FACTOR(),	\
			(__rect_in_points_points__).size.width * CC_CONTENT_SCALE_FACTOR(), (__rect_in_points_points__).size.height * CC_CONTENT_SCALE_FACTOR() )

/** @def CC_POINT_PIXELS_TO_POINTS
 Converts a rect in pixels to points
 */
#define CC_POINT_PIXELS_TO_POINTS(__pixels__)																		\
CGPointMake( (__pixels__).x / CC_CONTENT_SCALE_FACTOR(), (__pixels__).y / CC_CONTENT_SCALE_FACTOR())

/** @def CC_POINT_POINTS_TO_PIXELS
 Converts a rect in points to pixels
 */
#define CC_POINT_POINTS_TO_PIXELS(__points__)																		\
CGPointMake( (__points__).x * CC_CONTENT_SCALE_FACTOR(), (__points__).y * CC_CONTENT_SCALE_FACTOR())

/** @def CC_POINT_PIXELS_TO_POINTS
 Converts a rect in pixels to points
 */
#define CC_SIZE_PIXELS_TO_POINTS(__size_in_pixels__)																		\
CGSizeMake( (__size_in_pixels__).width / CC_CONTENT_SCALE_FACTOR(), (__size_in_pixels__).height / CC_CONTENT_SCALE_FACTOR())

/** @def CC_POINT_POINTS_TO_PIXELS
 Converts a rect in points to pixels
 */
#define CC_SIZE_POINTS_TO_PIXELS(__size_in_points__)																		\
CGSizeMake( (__size_in_points__).width * CC_CONTENT_SCALE_FACTOR(), (__size_in_points__).height * CC_CONTENT_SCALE_FACTOR())

#elif defined(__CC_PLATFORM_MAC)

/*****************************/
/** RETINA DISPLAY DISABLED **/
/*****************************/

#define CC_CONTENT_SCALE_FACTOR() 1
#define CC_RECT_PIXELS_TO_POINTS(__pixels__) __pixels__
#define CC_RECT_POINTS_TO_PIXELS(__points__) __points__
#define CC_SIZE_PIXELS_TO_POINTS(__pixels__) __pixels__
#define CC_SIZE_POINTS_TO_PIXELS(__points__) __points__
#define CC_POINT_PIXELS_TO_POINTS(__pixels__) __pixels__
#define CC_POINT_POINTS_TO_PIXELS(__points__) __points__

#endif // __CC_PLATFORM_MAC

/**********************/
/** Profiling Macros **/
/**********************/
#if CC_ENABLE_PROFILERS

#define CC_PROFILER_DISPLAY_TIMERS() [[CCProfiler sharedProfiler] displayTimers]
#define CC_PROFILER_PURGE_ALL() [[CCProfiler sharedProfiler] releaseAllTimers]

#define CC_PROFILER_START(__name__) CCProfilingBeginTimingBlock(__name__)
#define CC_PROFILER_STOP(__name__) CCProfilingEndTimingBlock(__name__)
#define CC_PROFILER_RESET(__name__) CCProfilingResetTimingBlock(__name__)

#define CC_PROFILER_START_CATEGORY(__cat__, __name__) do{ if(__cat__) CCProfilingBeginTimingBlock(__name__); } while(0)
#define CC_PROFILER_STOP_CATEGORY(__cat__, __name__) do{ if(__cat__) CCProfilingEndTimingBlock(__name__); } while(0)
#define CC_PROFILER_RESET_CATEGORY(__cat__, __name__) do{ if(__cat__) CCProfilingResetTimingBlock(__name__); } while(0)

#define CC_PROFILER_START_INSTANCE(__id__, __name__) do{ CCProfilingBeginTimingBlock( [NSString stringWithFormat:@"%08X - %@", __id__, __name__] ); } while(0)
#define CC_PROFILER_STOP_INSTANCE(__id__, __name__) do{ CCProfilingEndTimingBlock(    [NSString stringWithFormat:@"%08X - %@", __id__, __name__] ); } while(0)
#define CC_PROFILER_RESET_INSTANCE(__id__, __name__) do{ CCProfilingResetTimingBlock( [NSString stringWithFormat:@"%08X - %@", __id__, __name__] ); } while(0)

#else

#define CC_PROFILER_DISPLAY_TIMERS() do {} while (0)
#define CC_PROFILER_PURGE_ALL() do {} while (0)

#define CC_PROFILER_START(__name__)  do {} while (0)
#define CC_PROFILER_STOP(__name__) do {} while (0)
#define CC_PROFILER_RESET(__name__) do {} while (0)

#define CC_PROFILER_START_CATEGORY(__cat__, __name__) do {} while(0)
#define CC_PROFILER_STOP_CATEGORY(__cat__, __name__) do {} while(0)
#define CC_PROFILER_RESET_CATEGORY(__cat__, __name__) do {} while(0)

#define CC_PROFILER_START_INSTANCE(__id__, __name__) do {} while(0)
#define CC_PROFILER_STOP_INSTANCE(__id__, __name__) do {} while(0)
#define CC_PROFILER_RESET_INSTANCE(__id__, __name__) do {} while(0)

#endif

/*****************/
/** ARC Macros  **/
/*****************/
#if defined(__has_feature) && __has_feature(objc_arc)
// ARC (used for inline functions)
#define CC_ARC_RETAIN(value)	value
#define CC_ARC_RELEASE(value)	value = 0
#define CC_ARC_UNSAFE_RETAINED	__unsafe_unretained

#else
// No ARC
#define CC_ARC_RETAIN(value)	[value retain]
#define CC_ARC_RELEASE(value)	[value release]
#define CC_ARC_UNSAFE_RETAINED
#endif

/** @def CC_INCREMENT_GL_DRAWS_BY_ONE
 Increments the GL Draws counts by one.
 The number of calls per frame are displayed on the screen when the CCDirector's stats are enabled.
 */
extern NSUInteger __ccNumberOfDraws;
#define CC_INCREMENT_GL_DRAWS(__n__) __ccNumberOfDraws += __n__

/*******************/
/** Notifications **/
/*******************/
/** @def CCAnimationFrameDisplayedNotification
 Notification name when a CCSpriteFrame is displayed
 */
#define CCAnimationFrameDisplayedNotification @"CCAnimationFrameDisplayedNotification"


text:
<?xml version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE html
     PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
     "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

  <title>File: rake-0.7.1.rdoc</title>
  <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
  <meta http-equiv="Content-Script-Type" content="text/javascript" />
  <link rel="stylesheet" href="../../.././rdoc-style.css" type="text/css" media="screen" />

rake-0.7.1.rdoc

      Path:
      doc/release_notes/rake-0.7.1.rdoc

      Last Update:
      Sun Jun 06 10:49:21 -0500 2010

Rake 0.7.1 Released

Version 0.7.1 supplies a bug fix and a few minor enhancements.

Changes

Bug Fixes in 0.7.1

Changes in the exception reported for the FileUtils.ln caused safe_ln to
fail with a NotImplementedError. Rake 0.7.1 will now catch that error or
any StandardError and properly fall back to using <tt>cp</tt>.

New Features in 0.7.1

You can filter the results of the —task option by supplying an
optional regular expression. This allows the user to easily find a
particular task name in a long list of possible names.

Transforming procs in a rule may now return a list of prerequisites. This
allows more flexible rule formation.

FileList and String now support
a <tt>pathmap</tt> melthod that makes the transforming paths a bit easier.
See the API docs for <tt>pathmap</tt> for details.

The -f option without a value will disable the search for a Rakefile. This
allows the Rakefile to be defined entirely in a library (and loaded with
the -r option). The current working directory is not changed when this is
done.

What is Rake

Rake is a build tool similar to the make program in many ways. But instead
of cryptic make recipes, Rake uses standard Ruby code to declare tasks and
dependencies. You have the full power of a modern scripting language built
right into your build tool.

Availability

The easiest way to get and install rake is via RubyGems …

  gem install rake    (you may need root/admin privileges)

Otherwise, you can get it from the more traditional places:

Home Page:	rake.rubyforge.org/

Download:	rubyforge.org/project/showfiles.php?group_id=50

Thanks

As usual, it was input from users that drove a alot of these changes. The
following people either contributed patches, made suggestions or made
otherwise helpful comments. Thanks to …

James Britt and Assaph Mehr for reporting and helping to debug the safe_ln
issue.

[Validate]


text:
%   The following class contains parameter related to the transport
%   problems such as retardation, porosity, dispersion, etc, inside the
%   T_P_P property and parameter related to the Boundary Conditions.

classdef Problem_Transp_Definition
    properties
        T_P_P                               % Physical Transport Parameters Class
        Boundary_Condition                  % Boundary Conditions Class
    end

    methods

        %   Instantiate a Problem_Transp_Definition class.

        function this=Problem_Transp_Definition (Transport_Physical_Parameter, Boundary_Condition)
            this.T_P_P =Transport_Physical_Parameter;
            this.Boundary_Condition=Boundary_Condition;
        end
    end
end


text:
namespace Merchello.Core.Persistence.Repositories
{
    using System;
    using System.Collections.Generic;
    using System.Data;
    using System.Linq;

    using Merchello.Core.Logging;
    using Merchello.Core.Models;
    using Merchello.Core.Models.EntityBase;
    using Merchello.Core.Models.Rdbms;
    using Merchello.Core.Persistence.Factories;
    using Merchello.Core.Persistence.UnitOfWork;

    using Umbraco.Core;
    using Umbraco.Core.Cache;
    using Umbraco.Core.Logging;
    using Umbraco.Core.Persistence;
    using Umbraco.Core.Persistence.SqlSyntax;

    /// <summary>
    /// A repository for bulk SQL operations.
    /// </summary>
    /// <typeparam name="TEntity">
    /// The Type of entity
    /// </typeparam>
    /// <typeparam name="TDto">
    /// The type of Dto object
    /// </typeparam>
    internal abstract class MerchelloBulkOperationRepository<TEntity, TDto> : MerchelloPetaPocoRepositoryBase<TEntity>
        where TEntity : class, IEntity
        where TDto : class, IDto
    {
        /// <summary>
        /// The factory for creating the DTOs.
        /// </summary>
        private readonly Func<IEntityFactory<TEntity, TDto>> _factory;

        /// <summary>
        /// Initializes a new instance of the <see cref="MerchelloBulkOperationRepository{TEntity, TDto}"/> class.
        /// </summary>
        /// <param name="work">
        /// The database unit of work.
        /// </param>
        /// <param name="cache">
        /// The cache.
        /// </param>
        /// <param name="logger">
        /// The logger.
        /// </param>
        /// <param name="sqlSyntax">
        /// The SQL syntax.
        /// </param>
        /// <param name="factory">
        /// The factory.
        /// </param>
        protected MerchelloBulkOperationRepository(IDatabaseUnitOfWork work, CacheHelper cache, ILogger logger, ISqlSyntaxProvider sqlSyntax, Func<IEntityFactory<TEntity, TDto>> factory)
            : base(work, cache, logger, sqlSyntax)
        {
            _factory = factory;
        }

        protected void BulkInsertRecordsWithKey<T>(IEnumerable<T> collection)
        {
            //don't do anything if there are no records.
            if (collection.Any() == false)
                return;

            using (var tr = Database.GetTransaction())
            {
                BulkInsertRecordsWithKey(collection, tr, true);
            }
        }

        /// <summary>
        /// Performs the bulk insertion in the context of a current transaction with an optional parameter to complete the transaction
        /// when finished
        /// </summary>
        protected void BulkInsertRecordsWithKey<T>(IEnumerable<T> collection, Transaction tr, bool commitTrans = false)
        {
            //don't do anything if there are no records.
            var dtos = collection as T[] ?? collection.ToArray();
            if (dtos.Any() == false)
                return;

            try
            {
                //if it is sql ce or it is a sql server version less than 2008, we need to do individual inserts.
                var sqlServerSyntax = SqlSyntax as SqlServerSyntaxProvider;
                if (sqlServerSyntax == null || SqlSyntax is SqlCeSyntaxProvider)
                {
                    //SqlCe doesn't support bulk insert statements!
                    foreach (var poco in dtos)
                    {
                        Database.Insert(poco);
                    }
                }
                else
                {
                    string[] sqlStatements;
                    var cmds = GenerateBulkInsertCommand(dtos, Database.Connection, out sqlStatements);
                    for (var i = 0; i < sqlStatements.Length; i++)
                    {
                        using (var cmd = cmds[i])
                        {
                            cmd.CommandText = sqlStatements[i];
                            cmd.ExecuteNonQuery();
                        }
                    }
                }

                if (commitTrans)
                {
                    tr.Complete();
                }
            }
            catch
            {
                if (commitTrans)
                {
                    tr.Dispose();
                }
                throw;
            }
        }

        /// <summary>
        /// Executes a batch update.
        /// </summary>
        /// <param name="entities">
        /// The entities.
        /// </param>
        protected void ExecuteBatchUpdate(IEnumerable<TEntity> entities)
        {

            var entitiesArray = entities as TEntity[] ?? entities.ToArray();
            if (!entitiesArray.Any()) return;

            if (SqlSyntax is SqlCeSyntaxProvider)
            {
                foreach (var e in entitiesArray) PersistUpdatedItem(e);
                return;
            }

            var factory = _factory.Invoke();

            var dtos = new List<TDto>();

            foreach (var e in entitiesArray)
            {
                ApplyAddingOrUpdating(TransactionType.Update, e);
                dtos.Add(factory.BuildDto(e));
            }

            // get the table name and column counts
            var tableMeta = dtos.First().TableNameColumnCount();
            var tableName = tableMeta.Item1;
            var parameterCount = tableMeta.Item2;

            // Each record requires parameters, so we need to split into batches due to the
            // hard-coded 2100 parameter limit imposed by SQL Server
            var batchSize = 2100 / parameterCount;
            var batchCount = ((dtos.Count() - 1) / batchSize) + 1;
            for (var batchIndex = 0; batchIndex < batchCount; batchIndex++)
            {
                var sqlStatement = string.Empty;

                int paramIndex = 0;
                var parms = new List<object>();

                foreach (var dto in dtos.Skip(batchIndex * batchSize).Take(batchSize))
                {
                    var allColumns = dto.ColumnValues().ToArray();
                    var keyColumn = allColumns.First(x => x.Item1 == "pk"); // this is always named pk in Merchello
                    var paramColumns = allColumns.Where(x => x.Item1 != "pk");

                    sqlStatement += string.Format(" UPDATE [{0}] SET", tableName);
                    var firstParam = true;

                    foreach (var pc in paramColumns)
                    {
                        sqlStatement += string.Format("{0} [{1}] = @{2}", firstParam ? string.Empty : ",", pc.Item1, paramIndex++);
                        parms.Add(pc.Item2);
                        if (firstParam) firstParam = false;
                    }

                    sqlStatement += string.Format(" WHERE [pk] = @{0};", paramIndex++);

                    parms.Add(keyColumn.Item2);
                }

                // Commit the batch
                Database.Execute(sqlStatement, parms.ToArray());
            }
        }

        /// <summary>
        /// Calls AddingEntity or Updating Entity.
        /// </summary>
        /// <param name="transactionType">
        /// The transaction type.
        /// </param>
        /// <param name="entity">
        /// The entity.
        /// </param>
        /// <remarks>
        /// This needs to be done in the typed repository as some entities override the method defined in EntityBase
        /// </remarks>
        protected abstract void ApplyAddingOrUpdating(TransactionType transactionType, TEntity entity);

        private IDbCommand[] GenerateBulkInsertCommand<T>(
            IEnumerable<T> collection,
            IDbConnection connection,
            out string[] sql)
        {
            //A filter used below a few times to get all columns except result cols and not the primary key if it is auto-incremental
            Func<Database.PocoData, KeyValuePair<string, Database.PocoColumn>, bool> includeColumn = (data, column) =>
            {
                if (column.Value.ResultColumn) return false;
                if (data.TableInfo.AutoIncrement && column.Key == data.TableInfo.PrimaryKey) return false;
                return true;
            };

            var pd = Umbraco.Core.Persistence.Database.PocoData.ForType(typeof(T));
            var tableName = Database.EscapeTableName(pd.TableInfo.TableName);

            //get all columns to include and format for sql
            var cols = string.Join(", ",
                pd.Columns
                .Where(c => includeColumn(pd, c))
                .Select(c => tableName + "." + Database.EscapeSqlIdentifier(c.Key)).ToArray());

            var itemArray = collection.ToArray();

            //calculate number of parameters per item
            var paramsPerItem = pd.Columns.Count(i => includeColumn(pd, i));

            //Example calc:
            // Given: we have 4168 items in the itemArray, each item contains 8 command parameters (values to be inserterted)
            // 2100 / 8 = 262.5
            // Math.Floor(2100 / 8) = 262 items per trans
            // 4168 / 262 = 15.908... = there will be 16 trans in total

            //all items will be included if we have disabled db parameters
            var itemsPerTrans = Math.Floor(2000.00 / paramsPerItem);
            //there will only be one transaction if we have disabled db parameters
            var numTrans = Math.Ceiling(itemArray.Length / itemsPerTrans);

            var sqlQueries = new List<string>();
            var commands = new List<IDbCommand>();

            for (var tIndex = 0; tIndex < numTrans; tIndex++)
            {
                var itemsForTrans = itemArray
                    .Skip(tIndex * (int)itemsPerTrans)
                    .Take((int)itemsPerTrans);

                var cmd = Database.CreateCommand(connection, "");
                var pocoValues = new List<string>();
                var index = 0;
                foreach (var poco in itemsForTrans)
                {
                    var values = new List<string>();
                    //get all columns except result cols and not the primary key if it is auto-incremental
                    foreach (var i in pd.Columns.Where(x => includeColumn(pd, x)))
                    {
                        AddParam(cmd, i.Value.GetValue(poco), "@");
                        values.Add(string.Format("{0}{1}", "@", index++));
                    }
                    pocoValues.Add("(" + string.Join(",", values.ToArray()) + ")");
                }

                var sqlResult = string.Format("INSERT INTO {0} ({1}) VALUES {2}", tableName, cols, string.Join(", ", pocoValues));
                sqlQueries.Add(sqlResult);
                commands.Add(cmd);
            }

            sql = sqlQueries.ToArray();

            return commands.ToArray();
        }

        private void AddParam(IDbCommand cmd, object item, string ParameterPrefix)
        {
            // Convert value to from poco type to db type
            if (Umbraco.Core.Persistence.Database.Mapper != null && item != null)
            {
                var fn = Umbraco.Core.Persistence.Database.Mapper.GetToDbConverter(item.GetType());
                if (fn != null)
                    item = fn(item);
            }

            // Support passed in parameters
            var idbParam = item as IDbDataParameter;
            if (idbParam != null)
            {
                idbParam.ParameterName = string.Format("{0}{1}", ParameterPrefix, cmd.Parameters.Count);
                cmd.Parameters.Add(idbParam);
                return;
            }

            var p = cmd.CreateParameter();
            p.ParameterName = string.Format("{0}{1}", ParameterPrefix, cmd.Parameters.Count);
            if (item == null)
            {
                p.Value = DBNull.Value;
            }
            else
            {
                var t = item.GetType();
                if (t.IsEnum)       // PostgreSQL .NET driver wont cast enum to int
                {
                    p.Value = (int)item;
                }
                else if (t == typeof(Guid))
                {
                    p.Value = item.ToString();
                    p.DbType = DbType.String;
                    p.Size = 40;
                }
                else if (t == typeof(string))
                {
                    // out of memory exception occurs if trying to save more than 4000 characters to SQL Server CE NText column.
                    // Set before attempting to set Size, or Size will always max out at 4000
                    if ((item as string).Length + 1 > 4000 && p.GetType().Name == "SqlCeParameter")
                        p.GetType().GetProperty("SqlDbType").SetValue(p, SqlDbType.NText, null);

                    p.Size = (item as string).Length + 1;
                    if (p.Size < 4000)
                        p.Size = Math.Max((item as string).Length + 1, 4000);       // Help query plan caching by using common size

                    p.Value = item;
                }
                else if (t == typeof(AnsiString))
                {
                    // Thanks @DataChomp for pointing out the SQL Server indexing performance hit of using wrong string type on varchar
                    p.Size = Math.Max((item as AnsiString).Value.Length + 1, 4000);
                    p.Value = (item as AnsiString).Value;
                    p.DbType = DbType.AnsiString;
                }
                else if (t == typeof(bool))
                {
                    p.Value = ((bool)item) ? 1 : 0;
                }
                else if (item.GetType().Name == "SqlGeography") //SqlGeography is a CLR Type
                {
                    p.GetType().GetProperty("UdtTypeName").SetValue(p, "geography", null); //geography is the equivalent SQL Server Type
                    p.Value = item;
                }

                else if (item.GetType().Name == "SqlGeometry") //SqlGeometry is a CLR Type
                {
                    p.GetType().GetProperty("UdtTypeName").SetValue(p, "geometry", null); //geography is the equivalent SQL Server Type
                    p.Value = item;
                }
                else
                {
                    p.Value = item;
                }
            }

            cmd.Parameters.Add(p);
        }
    }
}


text:
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.ide.favoritesTreeView;

import com.intellij.ide.projectView.PresentationData;
import com.intellij.ide.util.treeView.AbstractTreeNode;
import com.intellij.openapi.project.Project;
import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * @author Konstantin Bulenkov
 */
public final class FavoritesRootNode extends AbstractTreeNode<String> {
  private List<AbstractTreeNode<?>> myFavoritesRoots;

  public FavoritesRootNode(Project project) {
    super(project, "");
  }

  @Override
  @NotNull
  public Collection<AbstractTreeNode<?>> getChildren() {
    if (myFavoritesRoots == null) {
      myFavoritesRoots = new ArrayList<>(FavoritesManager.getInstance(myProject).createRootNodes());
    }
    return myFavoritesRoots;
  }

  public void rootsChanged() {
    myFavoritesRoots = null;
  }

  @Override
  public void update(@NotNull final PresentationData presentation) {
  }
}


text:
import { Transform } from '@pixi/math';
import { expect } from 'chai';

describe('Transform', function ()
{
    describe('setFromMatrix', function ()
    {
        it('should decompose negative scale into rotation', function ()
        {
            const eps = 1e-3;

            const transform = new Transform();
            const parent = new Transform();
            const otherTransform = new Transform();

            transform.position.set(20, 10);
            transform.scale.set(-2, -3);
            transform.rotation = Math.PI / 6;
            transform.updateTransform(parent);

            otherTransform.setFromMatrix(transform.worldTransform);

            const position = otherTransform.position;
            const scale = otherTransform.scale;
            const skew = otherTransform.skew;

            expect(position.x).to.be.closeTo(20, eps);
            expect(position.y).to.be.closeTo(10, eps);
            expect(scale.x).to.be.closeTo(2, eps);
            expect(scale.y).to.be.closeTo(3, eps);
            expect(skew.x).to.equal(0);
            expect(skew.y).to.equal(0);
            expect(otherTransform.rotation).to.be.closeTo(-5 * Math.PI / 6, eps);
        });

        it('should decompose mirror into skew', function ()
        {
            const eps = 1e-3;

            const transform = new Transform();
            const parent = new Transform();
            const otherTransform = new Transform();

            transform.position.set(20, 10);
            transform.scale.set(2, -3);
            transform.rotation = Math.PI / 6;
            transform.updateTransform(parent);

            otherTransform.setFromMatrix(transform.worldTransform);

            const position = otherTransform.position;
            const scale = otherTransform.scale;
            const skew = otherTransform.skew;

            expect(position.x).to.be.closeTo(20, eps);
            expect(position.y).to.be.closeTo(10, eps);
            expect(scale.x).to.be.closeTo(2, eps);
            expect(scale.y).to.be.closeTo(3, eps);
            expect(skew.x).to.be.closeTo(5 * Math.PI / 6, eps);
            expect(skew.y).to.be.closeTo(Math.PI / 6, eps);
            expect(otherTransform.rotation).to.equal(0);
        });

        it('should apply skew before scale, like in adobe animate and spine', function ()
        {
            // this example looks the same in CSS and in pixi, made with pixi-animate by @bigtimebuddy

            const eps = 1e-3;

            const transform = new Transform();
            const parent = new Transform();
            const otherTransform = new Transform();

            transform.position.set(387.8, 313.95);
            transform.scale.set(0.572, 4.101);
            transform.skew.set(-0.873, 0.175);
            transform.updateTransform(parent);

            const mat = transform.worldTransform;

            expect(mat.a).to.be.closeTo(0.563, eps);
            expect(mat.b).to.be.closeTo(0.100, eps);
            expect(mat.c).to.be.closeTo(-3.142, eps);
            expect(mat.d).to.be.closeTo(2.635, eps);
            expect(mat.tx).to.be.closeTo(387.8, eps);
            expect(mat.ty).to.be.closeTo(313.95, eps);

            otherTransform.setFromMatrix(transform.worldTransform);

            const position = otherTransform.position;
            const scale = otherTransform.scale;
            const skew = otherTransform.skew;

            expect(position.x).to.be.closeTo(387.8, eps);
            expect(position.y).to.be.closeTo(313.95, eps);
            expect(scale.x).to.be.closeTo(0.572, eps);
            expect(scale.y).to.be.closeTo(4.101, eps);
            expect(skew.x).to.be.closeTo(-0.873, eps);
            expect(skew.y).to.be.closeTo(0.175, eps);
            expect(otherTransform.rotation).to.be.equal(0);
        });
    });
});


text:
namespace Mvc.Helper.Pagination
{
    public interface IPagination
    {
        int PageNumber { get; }

        int PageSize { get; }

        int TotalItems { get; }

        int TotalPages { get; }

        int FirstItem { get; }

        int LastItem { get; }

        bool HasPreviousPage { get; }

        bool HasNextPage { get; }
    }
}


text:
import sqlite3
import datetime
import dateutil.parser

working_dir = "/var/www/html/"
data_dir = "/home/pi/meteo/"

log_file_path = working_dir + "meteo.log"
db_path = data_dir + "meteo.db"

# Converts a string back the datetime structure
def getDateTimeFromISO8601String(s):
    d = dateutil.parser.parse(s)
    return d

def log_to_db ():
    conn = sqlite3.connect(db_path)
    c = conn.cursor()

    # Open log file
    lf = open(log_file_path, "r");

    # From each line of log file create a pairs of meteo data (time, value)
    for line in lf:
        # Parse line
        time, temp_in, humid_in, dew_in, temp_out, humid_out, dew_out, pressure = str(line).split(";")
        #c.execute("SELECT strftime('%s', (?), 'localtime')", (time, ))
        #int_time = (c.fetchone())[0]
        int_time = int (getDateTimeFromISO8601String(time).strftime("%s"))
        #time_ = getDateTimeFromISO8601String(time)
        #print int_time
        c.execute("INSERT INTO log (time, temp, humid, dew_point, pressure, temp_in, humid_in, dew_point_in) \
                   VALUES (?, ?, ?, ?, ?, ?, ?, ?)", (int_time, temp_out, humid_out, dew_out, pressure, temp_in, humid_in, dew_in))

    lf.close()
    conn.commit()
    conn.close()

def create_db ():
    conn = sqlite3.connect(db_path)
    c = conn.cursor()

    sql = "CREATE TABLE IF NOT EXISTS log (\n\
id INTEGER PRIMARY KEY ASC,\n\
time INT NOT NULL,\n\
temp REAL,\n\
humid INT,\n\
dew_point INT,\n\
pressure REAL,\n\
temp_in REAL,\n\
humid_in INT,\n\
dew_point_in INT)"

    c.execute(sql)

    conn.commit()
    conn.close()

print ("Creating database..")
create_db()
print ("Database OK")
print ("Copying from log file to database...")
log_to_db()
print ("Copy OK")


text:
try:
    from setuptools import setup, find_packages
except ImportError:
    from distutils.core import setup

from codecs import open
from os import path

here = path.abspath(path.dirname(__file__))

with open('VERSION', 'rb') as v:
    version = v.read().decode().strip()

with open('README.md', 'rb') as ld:
    long_description = ld.read().decode().strip()

setup(
    author='Maciej Gol',
    author_email='1kroolik1@gmail.com',
    classifiers=[
        'License :: OSI Approved :: MIT License',
        'Framework :: Django',
        'Programming Language :: Python',
    ],
    description='Celery integration for django-tenant-schemas and django-tenants',
    install_requires=[
        'celery',
    ],
    packages=find_packages(),
    python_requires=">=3.7",
    name='tenant-schemas-celery',
    license='MIT',
    long_description=long_description,
    long_description_content_type="text/markdown",
    url='https://github.com/maciej-gol/tenant-schemas-celery',
    version=version,
)


text:
layout: post
title: 机器学习模型训练应用工具
subtitle:
author: Bin Li
tags: []
image:
comments: true
published: false
---

## References
1. [allennlp](https://allennlp.org/tutorials)


text: search_result['4282']=["topic_0000000000000A34_events--.html","PaymentMethodDto Events",""];


text:
<!DOCTYPE html>

    <meta charset="utf-8" />
    <title>statsmodels.graphics.correlation.plot_corr_grid — statsmodels v0.10.1 documentation</title>
    <link rel="stylesheet" href="../_static/nature.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <link rel="stylesheet" type="text/css" href="../_static/graphviz.css" />

    <link rel="shortcut icon" href="../_static/statsmodels_hybi_favico.ico"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="next" title="statsmodels.graphics.plot_grids.scatter_ellipse" href="statsmodels.graphics.plot_grids.scatter_ellipse.html" />
    <link rel="prev" title="statsmodels.graphics.correlation.plot_corr" href="statsmodels.graphics.correlation.plot_corr.html" />
<link rel="stylesheet" href="../_static/examples.css" type="text/css" />
<link rel="stylesheet" href="../_static/facebox.css" type="text/css" />

Navigation

          index

          modules |

          next |

          previous |

Install
  |

Support
  |

Bugs
  |

Develop
  |

Examples
  |

FAQ
  |

Graphics |

statsmodels.graphics.correlation.plot_corr_grid¶

statsmodels.graphics.correlation.plot_corr_grid(dcorrs, titles=None, ncols=None, normcolor=False, xnames=None, ynames=None, fig=None, cmap='RdYlBu_r')[source]¶

Create a grid of correlation plots.

The individual correlation plots are assumed to all have the same
variables, axis labels can be specified only once.

Parameters

dcorrslist or iterable of ndarrays

List of correlation matrices.

titleslist of str, optional

List of titles for the subplots.  By default no title are shown.

ncolsint, optional

Number of columns in the subplot grid.  If not given, the number of
columns is determined automatically.

normcolorbool or tuple, optional

If False (default), then the color coding range corresponds to the
range of dcorr.  If True, then the color range is normalized to
(-1, 1).  If this is a tuple of two numbers, then they define the range
for the color bar.

xnameslist of str, optional

Labels for the horizontal axis.  If not given (None), then the
matplotlib defaults (integers) are used.  If it is an empty list, [],
then no ticks and labels are added.

ynameslist of str, optional

Labels for the vertical axis.  Works the same way as xnames.
If not given, the same names as for xnames are re-used.

figMatplotlib figure instance, optional

If given, this figure is simply returned.  Otherwise a new figure is
created.

cmapstr or Matplotlib Colormap instance, optional

The colormap for the plot.  Can be any valid Matplotlib Colormap
instance or name.

Returns

figMatplotlib figure instance

If ax is None, the created figure.  Otherwise the figure to which
ax is connected.

Examples

>>> import numpy as np
>>> import matplotlib.pyplot as plt
>>> import statsmodels.api as sm

In this example we just reuse the same correlation matrix several times.
Of course in reality one would show a different correlation (measuring a
another type of correlation, for example Pearson (linear) and Spearman,
Kendall (nonlinear) correlations) for the same variables.

>>> hie_data = sm.datasets.randhie.load_pandas()
>>> corr_matrix = np.corrcoef(hie_data.data.T)
>>> sm.graphics.plot_corr_grid([corr_matrix] * 8, xnames=hie_data.names)
>>> plt.show()

..plot :: plots/graphics_correlation_plot_corr_grid.py

Previous topic

statsmodels.graphics.correlation.plot_corr

Next topic

statsmodels.graphics.plot_grids.scatter_ellipse

This Page

Show Source

Quick search

    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" aria-labelledby="searchlabel" />
      <input type="submit" value="Go" />
    </form>

        © Copyright 2009-2018, Josef Perktold, Skipper Seabold, Jonathan Taylor, statsmodels-developers.
      Created using Sphinx 2.1.2.


text:
/**
 *
 */
package org.apache.eagle.jobrunning.crawler;

import java.io.IOException;
import java.io.InputStream;
import java.net.URLConnection;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipException;

import org.apache.eagle.jobrunning.config.RunningJobCrawlConfig;
import org.apache.eagle.jobrunning.counter.parser.JobCountersParser;
import org.apache.eagle.jobrunning.counter.parser.JobCountersParserImpl;
import org.apache.eagle.jobrunning.ha.HAURLSelector;
import org.apache.eagle.jobrunning.ha.HAURLSelectorImpl;
import org.apache.eagle.jobrunning.job.conf.JobConfParser;
import org.apache.eagle.jobrunning.job.conf.JobConfParserImpl;
import org.apache.eagle.jobrunning.util.InputStreamUtils;
import org.apache.eagle.jobrunning.util.JobUtils;
import org.apache.eagle.jobrunning.util.URLConnectionUtils;
import org.apache.commons.lang.time.DateUtils;
import org.apache.eagle.jobrunning.common.JobConstants;
import org.apache.eagle.jobrunning.yarn.model.AppWrapper;
import org.apache.eagle.jobrunning.yarn.model.JobCompleteWrapper;
import org.apache.eagle.jobrunning.yarn.model.JobCountersWrapper;
import org.apache.eagle.jobrunning.yarn.model.JobsWrapper;
import org.codehaus.jackson.JsonParser;
import org.codehaus.jackson.map.ObjectMapper;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import org.apache.eagle.jobrunning.url.JobCompleteCounterServiceURLBuilderImpl;
import org.apache.eagle.jobrunning.url.JobCompleteDetailServiceURLBuilderImpl;
import org.apache.eagle.jobrunning.url.JobCompletedConfigServiceURLBuilderImpl;
import org.apache.eagle.jobrunning.url.JobCountersServiceURLBuilderImpl;
import org.apache.eagle.jobrunning.url.JobDetailServiceURLBuilderImpl;
import org.apache.eagle.jobrunning.url.JobListServiceURLBuilderImpl;
import org.apache.eagle.jobrunning.url.JobRunningConfigServiceURLBuilderImpl;
import org.apache.eagle.jobrunning.url.JobStatusServiceURLBuilderImpl;
import org.apache.eagle.jobrunning.url.ServiceURLBuilder;
import org.apache.eagle.jobrunning.yarn.model.AppInfo;
import org.apache.eagle.jobrunning.yarn.model.AppsWrapper;
import org.apache.eagle.jobrunning.yarn.model.JobDetailInfo;

public class RMResourceFetcher implements ResourceFetcher{

	private static final Logger LOG = LoggerFactory.getLogger(RMResourceFetcher.class);
	private final HAURLSelector selector;
	private final String historyBaseUrl;
	private final ServiceURLBuilder jobListServiceURLBuilder;
	private final ServiceURLBuilder jobDetailServiceURLBuilder;
	private final ServiceURLBuilder jobCounterServiceURLBuilder;
	private final ServiceURLBuilder jobRunningConfigServiceURLBuilder;
	private final ServiceURLBuilder jobCompleteDetailServiceURLBuilder;
	private final ServiceURLBuilder jobCompleteCounterServiceURLBuilder;
	private final ServiceURLBuilder jobCompletedConfigServiceURLBuilder;
	private final ServiceURLBuilder jobStatusServiceURLBuilder;

	private static final int CONNECTION_TIMEOUT = 10000;
	private static final int READ_TIMEOUT = 10000;
	private static final String XML_HTTP_HEADER = "Accept";
	private static final String XML_FORMAT = "application/xml";

	private static final ObjectMapper OBJ_MAPPER = new ObjectMapper();

	static {
		OBJ_MAPPER.configure(JsonParser.Feature.ALLOW_NON_NUMERIC_NUMBERS, true);
	}

	public RMResourceFetcher(RunningJobCrawlConfig.RunningJobEndpointConfig config) {
		this.jobListServiceURLBuilder = new JobListServiceURLBuilderImpl();
		this.jobDetailServiceURLBuilder = new JobDetailServiceURLBuilderImpl();
		this.jobCounterServiceURLBuilder = new JobCountersServiceURLBuilderImpl();
		this.jobRunningConfigServiceURLBuilder = new JobRunningConfigServiceURLBuilderImpl();
		this.jobCompleteDetailServiceURLBuilder = new JobCompleteDetailServiceURLBuilderImpl();
		this.jobCompleteCounterServiceURLBuilder = new JobCompleteCounterServiceURLBuilderImpl();
		this.jobCompletedConfigServiceURLBuilder = new JobCompletedConfigServiceURLBuilderImpl();
		this.jobStatusServiceURLBuilder = new JobStatusServiceURLBuilderImpl();

		this.selector = new HAURLSelectorImpl(config.RMBasePaths, jobListServiceURLBuilder, JobConstants.CompressionType.GZIP);
		this.historyBaseUrl = config.HSBasePath;
	}

	private void checkUrl() throws IOException {
		if (!selector.checkUrl(jobListServiceURLBuilder.build(selector.getSelectedUrl(), JobConstants.JobState.RUNNING.name()))) {
			selector.reSelectUrl();
		}
	}

	private List<Object> doFetchApplicationsList(String state) throws Exception {
		List<AppInfo> result = null;
		InputStream is = null;
		try {
			checkUrl();
			final String urlString = jobListServiceURLBuilder.build(selector.getSelectedUrl(), state);
			LOG.info("Going to call yarn api to fetch running job list: " + urlString);
			is = InputStreamUtils.getInputStream(urlString, JobConstants.CompressionType.GZIP);
			final AppsWrapper appWrapper = OBJ_MAPPER.readValue(is, AppsWrapper.class);
			if (appWrapper != null && appWrapper.getApps() != null
					&& appWrapper.getApps().getApp() != null) {
				result = appWrapper.getApps().getApp();
				return Arrays.asList((Object)result);
			}
			return null;
		}
		finally {
			if (is != null) { try {is.close();} catch (Exception e){} }
		}
	}

	private List<Object> doFetchRunningJobInfo(String appID) throws Exception{
		InputStream is = null;
		InputStream is2 = null;
		try {
			final String urlString = jobDetailServiceURLBuilder.build(selector.getSelectedUrl(), appID);
			LOG.info("Going to fetch job detail information for " + appID + " , url: " + urlString);
			try {
				is = InputStreamUtils.getInputStream(urlString, JobConstants.CompressionType.GZIP);
			}
			catch (ZipException ex) {
				// Here if job already completed, it will be redirected to job history page and throw java.util.zip.ZipException
				LOG.info(appID + " has finished, skip this job");
				return null;
			}
			final JobsWrapper jobWrapper = OBJ_MAPPER.readValue(is, JobsWrapper.class);
			JobDetailInfo jobDetail = null;
			if (jobWrapper != null && jobWrapper.getJobs() != null && jobWrapper.getJobs().getJob() != null
				&& jobWrapper.getJobs().getJob().size() > 0) {
				jobDetail = jobWrapper.getJobs().getJob().get(0);
			}
			final String urlString2 = jobCounterServiceURLBuilder.build(selector.getSelectedUrl(), appID);
			LOG.info("Going to fetch job counters for application " + appID + " , url: " + urlString2);
			is2 = InputStreamUtils.getInputStream(urlString2, JobConstants.CompressionType.GZIP);
			final JobCountersWrapper jobCounterWrapper = OBJ_MAPPER.readValue(is2,JobCountersWrapper.class);

			return Arrays.asList(jobDetail, jobCounterWrapper);
		}
		finally {
			if (is != null) { try {is.close();} catch (Exception e){} }
			if (is2 != null) { try {is2.close();} catch (Exception e){} }
		}
	}

	private List<Object> doFetchCompleteJobInfo(String appId) throws Exception{
		InputStream is = null;
		InputStream is2 = null;
		try {
			checkUrl();
			String jobID = JobUtils.getJobIDByAppID(appId);
			String urlString = jobCompleteDetailServiceURLBuilder.build(selector.getSelectedUrl(), jobID);
			LOG.info("Going to fetch job completed information for " + jobID + " , url: " + urlString);
			is = InputStreamUtils.getInputStream(urlString, JobConstants.CompressionType.GZIP);
			final JobCompleteWrapper jobWrapper = OBJ_MAPPER.readValue(is, JobCompleteWrapper.class);

			String urlString2 = jobCompleteCounterServiceURLBuilder.build(historyBaseUrl, jobID);
			LOG.info("Going to fetch job completed counters for " + jobID + " , url: " + urlString2);
			is2 = InputStreamUtils.getInputStream(urlString2, JobConstants.CompressionType.NONE, (int) (2 * DateUtils.MILLIS_PER_MINUTE));
			final Document doc = Jsoup.parse(is2, StandardCharsets.UTF_8.name(), urlString2);
			JobCountersParser parser = new JobCountersParserImpl();
			Map<String, Long> counters = parser.parse(doc);
			return Arrays.asList(jobWrapper, counters);
		}
		finally {
			if (is != null) { try {is.close();} catch (Exception e){}  }
			if (is2 != null) { try {is2.close();} catch (Exception e){}  }
		}
	}

	private List<Object> doFetchRunningJobConfiguration(String appID) throws Exception {
		InputStream is = null;
		try {
			checkUrl();
			String jobID = JobUtils.getJobIDByAppID(appID);
			String urlString = jobRunningConfigServiceURLBuilder.build(selector.getSelectedUrl(), jobID);
			LOG.info("Going to fetch job completed information for " + jobID + " , url: " + urlString);
			final URLConnection connection = URLConnectionUtils.getConnection(urlString);
			connection.setRequestProperty(XML_HTTP_HEADER, XML_FORMAT);
			connection.setConnectTimeout(CONNECTION_TIMEOUT);
			connection.setReadTimeout(READ_TIMEOUT);
			is = connection.getInputStream();
			Map<String, String> configs = XmlHelper.getConfigs(is);
			return Arrays.asList((Object)configs);
		}
		finally {
			if (is != null) { try {is.close();} catch (Exception e){}  }
		}
	}

	private List<Object> doFetchCompletedJobConfiguration(String appID) throws Exception {
		InputStream is = null;
		try {
			String urlString = jobCompletedConfigServiceURLBuilder.build(historyBaseUrl, JobUtils.getJobIDByAppID(appID));
			is = InputStreamUtils.getInputStream(urlString, JobConstants.CompressionType.NONE);
			final Document doc = Jsoup.parse(is, "UTF-8", urlString);
			JobConfParser parser = new JobConfParserImpl();
			Map<String, String> configs = parser.parse(doc);
			return Arrays.asList((Object)configs);
		}
		finally {
			if (is != null) { try {is.close();} catch (Exception e){}  }
		}
	}

	public boolean checkIfJobIsRunning(String appID) throws Exception{
		InputStream is = null;
		try {
			checkUrl();
			final String urlString = jobStatusServiceURLBuilder.build(selector.getSelectedUrl(), appID);
			LOG.info("Going to call yarn api to fetch job status: " + urlString);
			is = InputStreamUtils.getInputStream(urlString, JobConstants.CompressionType.GZIP);
			final AppWrapper appWrapper = OBJ_MAPPER.readValue(is, AppWrapper.class);
			if (appWrapper != null && appWrapper.getApp() != null) {
				AppInfo result = appWrapper.getApp();
				if (result.getState().equals(JobConstants.JOB_STATE_RUNNING)) {
					return true;
				}
				return false;
			}
			else {
				LOG.error("The status of " + appID + " is not available");
				throw new IllegalStateException("The status of " + appID + " is not available");
			}
		}
		finally {
			if (is != null) { try {is.close();} catch (Exception e){}  }
		}
	}

	public List<Object> getResource(JobConstants.ResourceType resoureType, Object... parameter) throws Exception{
		switch(resoureType) {
			case JOB_LIST:
				return doFetchApplicationsList((String)parameter[0]);
			case JOB_RUNNING_INFO:
				//parameter[0]= appId
				return doFetchRunningJobInfo((String)parameter[0]);
			case JOB_COMPLETE_INFO:
				//parameter[0]= appId
				return doFetchCompleteJobInfo((String)parameter[0]);
			case JOB_CONFIGURATION:
				//parameter[0]= appId
				boolean isRunning = checkIfJobIsRunning((String)parameter[0]);
				if (isRunning)
					return doFetchRunningJobConfiguration((String)parameter[0]);
				else
					return doFetchCompletedJobConfiguration((String)parameter[0]);
			default:
				throw new Exception("Not support ressourceType :" + resoureType);
		}
	}
}


text:
typedef NS_ENUM(NSUInteger, LineSDKRequestMethod) {
    LineSDKRequestMethodGet,
    LineSDKRequestMethodPost,
    LineSDKRequestMethodDelete,
    LineSDKRequestMethodPut
};

@class LineSDKAccessToken;

NS_ASSUME_NONNULL_BEGIN
@protocol LineSDKRequestProtocol <NSObject>

@property (nonatomic, assign, readonly) LineSDKRequestMethod method;
@property (nonatomic, strong, readonly) NSString *path;
@property (nonatomic, strong, nullable, readonly) NSString *contentType;

- (nullable NSData *)bodyData;
- (nullable NSDictionary<NSString *, NSString *> *)queryParameters;
- (nullable LineSDKAccessToken *)accessToken;
- (void)setAccessToken:(LineSDKAccessToken * _Nullable)accessToken;

@end

@protocol LineSDKAuthenticationRefreshDelegate <NSObject>

- (void)refreshTokenWithAccessToken:(nullable LineSDKAccessToken *)accessToken
                         completion:(void(^)(LineSDKAccessToken * _Nullable accessToken, NSError * _Nullable error))completion;

@end

NS_ASSUME_NONNULL_END


text:
<?php

/**
 * @file
 * Main view template.
 *
 * Variables available:
 * - $classes_array: An array of classes determined in
 *   template_preprocess_views_view(). Default classes are:
 *     .view
 *     .view-[css_name]
 *     .view-id-[view_name]
 *     .view-display-id-[display_name]
 *     .view-dom-id-[dom_id]
 * - $classes: A string version of $classes_array for use in the class attribute
 * - $css_name: A css-safe version of the view name.
 * - $css_class: The user-specified classes names, if any
 * - $header: The view header
 * - $footer: The view footer
 * - $rows: The results of the view query, if any
 * - $empty: The empty text to display if the view is empty
 * - $pager: The pager next/prev links to display, if any
 * - $exposed: Exposed widget form/info to display
 * - $feed_icon: Feed icon to display, if any
 * - $more: A link to view more, if any
 *
 * @ingroup views_templates
 */
?>
<div class="<?php print $classes; ?>">

    Hide

  <?php print render($title_prefix); ?>
  <?php if ($title): ?>
    <?php print $title; ?>
  <?php endif; ?>
  <?php print render($title_suffix); ?>
  <?php if ($header): ?>

      <?php print $header; ?>

  <?php endif; ?>

  <?php if ($exposed): ?>

      <?php print $exposed; ?>

  <?php endif; ?>

  <?php if ($attachment_before): ?>

      <?php print $attachment_before; ?>

  <?php endif; ?>

  <?php if ($rows): ?>

      <?php print $rows; ?>

  <?php elseif ($empty): ?>

      <?php print $empty; ?>

  <?php endif; ?>

  <?php if ($pager): ?>
    <?php print $pager; ?>
  <?php endif; ?>

  <?php if ($attachment_after): ?>

      <?php print $attachment_after; ?>

  <?php endif; ?>

  <?php if ($more): ?>
    <?php print $more; ?>
  <?php endif; ?>

  <?php if ($footer): ?>

      <?php print $footer; ?>

  <?php endif; ?>

  <?php if ($feed_icon): ?>

      <?php print $feed_icon; ?>

  <?php endif; ?>

<?php /* class view */ ?>


text:
<!doctype html>

        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <title></title>
        <meta name="description" content="">
        <meta name="viewport" content="width=device-width, initial-scale=1">

        <link rel="stylesheet" href="css/screen.css">

                    ☰ Menü

                        Perspektiven

Neueinstellung

Ausbildung

Weiterbildung

Work-Life-Balance

Sozialleistungen

Warum KMU zu Ihnen passt

Stellenangebote

Jetzt bewerben

Headline

Subline

Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim.

                    Erfahren Sie mehr

Headline

USP

USP

USP

Headline

1

2

Headline

Testimonial

Testimonial

Testimonial

Testimonial

Headline

Kontakt

Anfahrt

Impressum

Datenschutz

        <link href='http://fonts.googleapis.com/css?family=Roboto:400,100,300,500,700,900' rel='stylesheet' type='text/css'>


text:
/************************************************************************************

Filename    :   BossController.cs
Content     :   Controller for enemy boss
Created     :   9 June 2014
Authors     :   Chris Julian Zaharia

************************************************************************************/

using UnityEngine;
using System.Collections;

public class BossController : MonoBehaviour {
    public float health = 3;
    public float followSpeed = 3;
    public float followAngularSpeed = 30;
    public float playerCarrySpeed = 5;                              // Walking speed of player when carrying boss
    public float playerCarryTurnSpeed = 2;                          // Turn speed of player when carrying boss
    public float minHurtAltitude = 0;                               // The min altitude that boss must be at to be hurt by player
    public float heldFixedRotationX;                                // Keep the boss rotated on axis X at this value when held by player
    public float hurtDuration = 3;                                  // Seconds where boss is in hurt stage
    public GameObject terrain;                                      // Terrain that the boss stands on
    public GameObject grabPerimeter;                                // Area where boss will grab player if player enters the area
    public float minDistanceGrabPermimeter = 4;	                    // If player distance from grab perimeter less then this, player is grabbed
    public float standBackUpSpeed = 0.05f;                          // Time taken for boss to stand back up when grounded
    public float lowerYExitArenaBoundary;                           // If player leaves this boundary, boss resets
    public Vector3 endMarkerJumpOffset = new Vector3(0, 0, 0);      // Offset where boss will jump to from spawn point
    public Vector3 starSpawnOffset = new Vector3 (0, 2, 0);
    public float waitToSpawnStar = 0;                               // Time to wait until star is spawned after boss defeat
    public float jumpDropSpeed = 3f;                                    // Speed of boss dropping from jump

    // Audio clips
    public AudioClip hurtAudioClip;                                 // Sound when boss gets hurt
    public AudioClip explosionAudioClip;

    // Animation names
    public string heldAnimationName;                                // Name of animation clip when player holds boss
    public float heldAnimationSpeed;                                // How fast animation runs when boss held by player
    public string grabAnimationName;                                // Name of animation clip when boss grabs player
    public string throwAnimationName;                               // Name of animation clip when boss throws player
    public string recoverAnimationName;                             // Name of animation clip where boss recovers from being hurt
    public string jumpAnimationName;                                // Name of animation clip where boss is jumping
    public string idleAnimationName;                                // Name of animation clip where boss is idle

    protected NavMeshAgent agent;
    protected GameObject player;
    protected CharacterMotor motor;
    protected FPSInputController playerController;
    protected PlayerLook playerLook;
    protected HydraLook playerHydraLook;
    protected PlayerHealth playerHealth;
    protected SixenseHandControllerExtender[] playerSixenseHandControllers;
    protected LeapGrabbableExtender leapGrabbable;
    protected Movement movement;
    protected GameObject explosion;
    protected GameObject star;
    protected string defaultTag;                                // object's current tag, assumes this tag handles if object is grabbable
    protected string defaultAnimationName;
    protected float defaultHealth;
    protected float defaultSpeed;
    protected float defaultAngularSpeed;
    protected bool initBattle = false;
    protected bool startedBattle = false;
    protected bool isHeldByPlayer;                              // If boss is currently being held by player
    protected bool wasHeldByPlayer;                             // If boss has been held by player before
    protected bool isGrounded;
    protected bool isGrabbingPlayer = false;
    protected bool canGrabPlayer = false;
    protected bool isThrowingPlayer = false;
    protected bool isStandingBackUp = false;
    protected bool dead;                                        // If enemy is dead

    // These are all the movement types that the enemy can do
    protected enum Movement{Follow, Freeze, Grab, Idle, Throw};

    // Throwing player movement
    protected GameObject startMarkerThrowPlayer;
    protected GameObject endMarkerThrowPlayer;
    protected float startTimeThrowPlayer;
    protected float journeyLengthThrowPlayer;

    // Boss jump movement
    protected GameObject startMarkerJump;
    protected GameObject endMarkerJump;
    protected float startTimeJump;
    protected float journeyLengthJump;
    protected bool isJumpingToSpawnPoint;
    protected bool isLandingFromJump;

    // Object spawn location
    protected Vector3 spawnPosition;
    protected Quaternion spawnRotation;

	protected virtual void Awake () {
		agent = this.GetComponent<NavMeshAgent> ();

		player = GameObject.FindWithTag("Player");
		motor = player.GetComponent<CharacterMotor> ();
		playerController = player.GetComponent<FPSInputController> ();
		playerLook = player.GetComponent<PlayerLook> ();
		playerHydraLook = player.GetComponent<HydraLook> ();
		playerHealth = player.GetComponent<PlayerHealth> ();
        playerSixenseHandControllers = player.GetComponentsInChildren<SixenseHandControllerExtender> ();
        leapGrabbable = GetComponent<LeapGrabbableExtender> ();

        startMarkerThrowPlayer = new GameObject();
        endMarkerThrowPlayer = new GameObject ();

        startMarkerJump = new GameObject();
        endMarkerJump = new GameObject ();

        spawnPosition = transform.position;
        spawnRotation = transform.rotation;

        defaultAnimationName = GetComponent<Animation>().clip.name;
		defaultHealth = health;
		defaultSpeed = agent.speed;
		defaultAngularSpeed = agent.angularSpeed;

		movement = Movement.Idle;

		defaultTag = gameObject.tag;
	}

	protected virtual void Start () {
		health = defaultHealth;
        Init ();
	}

    protected void Init() {
        leapGrabbable.canGrab = false;
        isHeldByPlayer = false;
        wasHeldByPlayer = false;
        isGrounded = false;
        isJumpingToSpawnPoint = false;
        isLandingFromJump = false;

        TriggerIgnorePlayerHandColliders (true);

        gameObject.tag = "Untagged";

    }

    protected virtual void Update () {
        if (dead) {
            return;
        }

		if (initBattle && !startedBattle) {
			TriggerBattle(true);
		}

		IsPlayerHoldingEnemy ();

		IsPlayerInGrabPermimeter ();

        if (startedBattle) {
            IsPlayerOutsideArena();
        }

		switch (movement)
		{
		case Movement.Follow:
			FollowPlayer ();
			break;
		case Movement.Freeze:
			Freeze ();
			break;
		}

		if (isThrowingPlayer) {
			float distCovered = (Time.time - startTimeThrowPlayer) * 20.0f;
			float fracJourney = distCovered / journeyLengthThrowPlayer;
			player.transform.position = Vector3.Lerp(startMarkerThrowPlayer.transform.position, endMarkerThrowPlayer.transform.position, fracJourney);

			if (fracJourney >= 1f) {
				isGrabbingPlayer = false;
				isThrowingPlayer = false;
                followSpeed = defaultSpeed;
                GetComponent<Rigidbody>().constraints = RigidbodyConstraints.None;
				GetComponent<Animation>().Play ("Walk");
			}
		}

        // Transition between fallen on back to standing up
        if (isStandingBackUp) {
            transform.rotation = Quaternion.Lerp (transform.rotation, Quaternion.Euler(new Vector3 (0, transform.rotation.y, transform.rotation.z)), standBackUpSpeed);
        }

        // Jump to above spawn point
        if (isJumpingToSpawnPoint) {
            float distCovered = (Time.time - startTimeJump) * 20.0f;
            float fracJourney = distCovered / journeyLengthJump;
            transform.position = Vector3.Lerp(startMarkerJump.transform.position, endMarkerJump.transform.position, fracJourney);

            if (transform.position == endMarkerJump.transform.position) {
                transform.rotation = spawnRotation;
                isJumpingToSpawnPoint = false;
                GetComponent<Animation>().Play(idleAnimationName);
                isLandingFromJump = true;
            }
        }

        // Landing from jump
        if (isLandingFromJump) {
            float step = jumpDropSpeed * Time.deltaTime;
            transform.position = Vector3.MoveTowards(transform.position, spawnPosition, step);

            if (transform.position == spawnPosition) {
                isLandingFromJump = false;
                GetComponent<Animation>().Play(idleAnimationName);
                TriggerBattle(false);
            }
        }
	}

	protected void OnCollisionEnter(Collision col) {
        if (col.gameObject.name == terrain.name && !isHeldByPlayer && wasHeldByPlayer && !isGrounded) {
            canGrabPlayer = false;
            if (transform.position.y > minHurtAltitude) {
                StartCoroutine(Hurt());
            } else {
                isGrounded = true;
                StartCoroutine (SitBackUp (false));
            }
		}
	}

	protected IEnumerator Hurt () {
        gameObject.tag = "Untagged";
        GetComponent<Rigidbody>().constraints = RigidbodyConstraints.FreezeAll;
		isGrounded = true;
		health -= 1;
		if (!GetComponent<AudioSource>().isPlaying) {
			GetComponent<AudioSource>().clip = hurtAudioClip;
			GetComponent<AudioSource>().Play();
		}
		yield return new WaitForSeconds(hurtDuration);
        if (health != 0) {
            GetComponent<Rigidbody>().constraints = RigidbodyConstraints.None;
            GetComponent<Rigidbody>().freezeRotation = false;
            StartCoroutine (SitBackUp (true));
        } else {
            StartCoroutine(Death());
        }
	}

	// Boss will return back to their feet after fallen onto ground
	protected IEnumerator SitBackUp (bool wasHurt) {
		GetComponent<Animation>().Play ("Recover");
		float animLength = GetComponent<Animation>().clip.length;

        isStandingBackUp = true;
		yield return new WaitForSeconds(animLength);
        isStandingBackUp = false;

		// Stop ignoring player colliders
		TriggerIgnorePlayerColliders(false);

        wasHeldByPlayer = false;
        isGrounded = false;
        canGrabPlayer = true;

        // If boss was just hurt
        if (wasHurt) {
            agent.enabled = true;
            GetComponent<Animation>().Play ("Walk");
            movement = Movement.Follow;
            gameObject.tag = defaultTag;
        } else {
            JumpBackToArena ();
        }
    }

    protected void JumpBackToArena() {
        GetComponent<Animation>().Play (jumpAnimationName);

        startMarkerJump.transform.position = transform.position;
        endMarkerJump.transform.position = spawnPosition + endMarkerJumpOffset;
        startTimeJump = Time.time;
        journeyLengthJump = Vector3.Distance(startMarkerJump.transform.position, endMarkerJump.transform.position);

        isJumpingToSpawnPoint = true;
    }

    protected virtual void TriggerBattle(bool state) {
        if (state) {
            startedBattle = true;
            leapGrabbable.canGrab = true;
            GetComponent<Rigidbody>().useGravity = true;
            GetComponent<Rigidbody>().isKinematic = false;
            canGrabPlayer = true;
            GetComponent<Animation>().Play ("Walk");
            agent.enabled = true;
            StartCoroutine (StartFollowingPlayer (3));
        } else {
            startedBattle = false;
            initBattle = false;
            leapGrabbable.canGrab = false;
            GetComponent<Rigidbody>().useGravity = false;
            GetComponent<Rigidbody>().isKinematic = true;
            canGrabPlayer = false;
            agent.enabled = false;
            movement = Movement.Idle;
            transform.position = spawnPosition;
            transform.rotation = spawnRotation;
            Init ();
            TriggerBossBattle triggerBossBattle = (TriggerBossBattle) FindObjectOfType(typeof(TriggerBossBattle));
            triggerBossBattle.SetAudioPlaying(false);
            SceneManager sceneManager = (SceneManager) FindObjectOfType(typeof(SceneManager));
            GameObject worldTheme = GameObject.Find ("Theme");
            worldTheme.GetComponent<AudioSource>().clip = sceneManager.sceneAudioClip;
            worldTheme.GetComponent<AudioSource>().Play ();
        }
    }

	protected IEnumerator StartFollowingPlayer (float length) {
		agent.speed = 1;
		agent.angularSpeed = 60;
		agent.SetDestination (player.transform.position);
		yield return new WaitForSeconds(length);
		movement = Movement.Follow;
		gameObject.tag = defaultTag;

	}

	// If player is holding enemy then stop any enemy movement
	protected void IsPlayerHoldingEnemy() {
		if (IsHoldingEnemy ()) {
			movement = Movement.Freeze;
			LimitPlayerAbilities(true);
			GetComponent<Rigidbody>().freezeRotation = true;

			// Ignore player colliders when held by player
			TriggerIgnorePlayerColliders(true);
		} else {
			LimitPlayerAbilities(false);
		}
	}

	// Grab player if within grab perimeter
	protected void IsPlayerInGrabPermimeter () {
		float dist = Vector3.Distance(player.transform.position, grabPerimeter.transform.position);

        if (dist < minDistanceGrabPermimeter && !isGrabbingPlayer && canGrabPlayer) {
            StartCoroutine(GrabPlayer ());
            Vector3 offset = new Vector3 (-5.0f, 3f, 0f);
            player.transform.position = transform.position + offset;
            player.transform.forward = transform.forward;
		}
	}

    protected void IsPlayerOutsideArena () {
        if (player.transform.position.y <= lowerYExitArenaBoundary) {
            GetComponent<Animation>().Play(defaultAnimationName);
            TriggerBattle(false);
        }
    }

	// Boss grabs player
	protected IEnumerator GrabPlayer () {
		GetComponent<Animation>().Play (grabAnimationName);
		isGrabbingPlayer = true;
        followSpeed = 0;
        GetComponent<Rigidbody>().constraints = RigidbodyConstraints.FreezeAll;
		yield return new WaitForSeconds(GetComponent<Animation>().clip.length);
		ThrowPlayer ();
	}

	protected void ThrowPlayer () {
		if (isThrowingPlayer) {
			return;
		}
		GetComponent<Animation>().Play (throwAnimationName);
		startMarkerThrowPlayer.transform.position = player.transform.position;
		endMarkerThrowPlayer.transform.position = startMarkerThrowPlayer.transform.position + new Vector3 (-20f, 10f, 0f);
		startTimeThrowPlayer = Time.time;
		journeyLengthThrowPlayer = Vector3.Distance(startMarkerThrowPlayer.transform.position, endMarkerThrowPlayer.transform.position);
		isThrowingPlayer = true;
	}

	protected bool IsHoldingEnemy () {
        bool isHoldingEnemy = false;
        foreach (SixenseHandControllerExtender playerHandController in playerSixenseHandControllers) {
			if (gameObject == playerHandController.GetClosestObject() && playerHandController.IsHoldingObject()) {
                isHoldingEnemy = true;
			}
        }

        LeapGrabbingHandExtender[] leapHands = GameObject.FindObjectsOfType<LeapGrabbingHandExtender> ();

        foreach (LeapGrabbingHandExtender leapHand in leapHands) {
            if (leapHand.IsPinched()) {
                Collider col = leapHand.GetActiveObject();
                if (col && col.gameObject == gameObject) {
                    isHoldingEnemy = true;
                }
            }
        }

        if (isHoldingEnemy) {
            isHeldByPlayer = true;
            wasHeldByPlayer = true;
            GetComponent<Animation>().Play (heldAnimationName);
            GetComponent<Animation>()[heldAnimationName].speed = heldAnimationSpeed;
            if (heldFixedRotationX >= -360 && heldFixedRotationX <= 360) {
                transform.rotation = Quaternion.Euler(new Vector3 (heldFixedRotationX, transform.rotation.eulerAngles.y, transform.rotation.eulerAngles.z));
            }
            return true;
        } else {
            isHeldByPlayer = false;
            return false;
        }

	}

    // Trigger slowing down and preventing jumping for player
	protected void LimitPlayerAbilities (bool change) {
		if (change) {
			motor.movement.maxForwardSpeed = playerCarrySpeed;
			motor.movement.maxBackwardsSpeed = playerCarrySpeed;
			playerLook.sensitivityX = playerCarryTurnSpeed;
			playerHydraLook.sensitivityX = playerCarryTurnSpeed;
            playerController.JumpEnabled = false;
		} else {
			motor.movement.maxForwardSpeed = playerController.getDefaultMaxForwardSpeed();
			motor.movement.maxBackwardsSpeed = playerController.getDefaultMaxForwardSpeed();
			playerLook.sensitivityX = playerLook.getDefaultSensitivityX();
            playerHydraLook.sensitivityX = playerHydraLook.getDefaultSensitivityX();
            playerController.JumpEnabled = true;
		}
	}

	protected virtual void FollowPlayer() {
        if (!agent.enabled)
            return;

		agent.SetDestination (player.transform.position);
		agent.speed = followSpeed;
		agent.angularSpeed = followAngularSpeed;
	}

	protected virtual void Freeze () {
		agent.enabled = false;
	}

	protected void TriggerIgnorePlayerHandColliders (bool state) {
        foreach (SixenseHandControllerExtender playerHandController in playerSixenseHandControllers) {
			Collider[] cols = GetComponentsInChildren<Collider>();
			Collider[] playerHandCols = playerHandController.GetComponentsInChildren<Collider>();

			foreach (Collider playerHandCol in playerHandCols) {
				foreach (Collider col in cols) {
					Physics.IgnoreCollision(playerHandCol, col, state);
				}
			}
		}
	}

	protected void TriggerIgnorePlayerColliders (bool state) {
		Collider[] cols = GetComponentsInChildren<Collider>();
		Collider[] playerCols = player.GetComponentsInChildren<Collider>();

		foreach (Collider playerCol in playerCols) {
			foreach (Collider col in cols) {
				Physics.IgnoreCollision(playerCol, col, state);
			}
		}

		// Always ignore player hand colliders
		if (!state) {
			TriggerIgnorePlayerHandColliders(true);
		}
	}

	public void SetInitBattle(bool state) {
		initBattle = state;
	}

    protected IEnumerator Death () {
        dead = true;
        yield return new WaitForSeconds(waitToSpawnStar);
        explosion = (GameObject) Instantiate(Resources.Load("Explosion"));
        explosion.transform.position = transform.position;
        TriggerBossBattle triggerBossBattle = (TriggerBossBattle) FindObjectOfType(typeof(TriggerBossBattle));
        triggerBossBattle.worldTheme.GetComponent<AudioSource>().Stop ();
        Disable ();
        SpawnStar ();
    }

    protected void SpawnStar () {
        star = (GameObject) Instantiate(Resources.Load("Star"));
        StarController starController = star.GetComponent<StarController> ();
        star.transform.position = transform.position + starSpawnOffset;
        starController.Spawn ();

    }

    protected void Disable() {
        Renderer[] renderers = gameObject.GetComponentsInChildren<Renderer>();
        foreach (Renderer renderer in renderers) {
            renderer.enabled = false;
        }

        Collider[] colliders = gameObject.GetComponentsInChildren<Collider>();
        foreach (Collider col in colliders) {
            col.enabled = false;
        }
    }
}


text:
export const LOADED_HOME_INFO = 'LOADED_HOME_INFO';
export const LOAD_HOME_INFO = 'LOAD_HOME_INFO';
export const CREATE_NOTIFICATION = 'CREATE_NOTIFICATION';
export const CLEAR_NOTIFICATION = 'CLEAR_NOTIFICATION';


text:
<title>Ankit Patel's homepage </title>

ANKIT  C.  PATEL

914, EAST STATE STREET,

ITHACA. NY-14850.

(607) 277-3812

apatel@cs.cornell.edu

[

	Personal
 |
    Photo Galleria
 |
   Chronologia Curriculum Vitae

]

	Cornell University

1996

Resume

Department of Computer Science and Courses Enrolled

Graduate Research Assistant for Prof. Brian Smith in the Multimedia Group Project Zeno

 Canvas3d  : A toolkit for interactive, platform-independent development of high-performance 3D graphics in multimedia and virtual reality applications.

Virtual Reality Video Conferencing

Multimedia Systems :

Readings, Project and Assignments

Project :  Kernel Endpoint for U-Net

An Annotated Bibliography on `Common Object Request Broker Architecture'(CORBA)

A Critique on `Understanding the limitations of Causally and Totally Ordered Communication' by David R. Cheriton and Dale Skeen.

	Carnegie-Mellon Summer School of Computer Science

1996

World-Wide Web Technologies  [Spring'96 Course Link]

Real-Time OS Support for Multimedia

Maharaja Sayajirao University

1991-95

Academics

Friends from Techo

Reliance Industries Limited

1995

Job Profile

Life at Reliance


text:
package cogdebugger.ui.components

import scala.swing.Component
import scala.swing.event.ValueChanged
import javax.swing.{SpinnerNumberModel, JSpinner, SpinnerModel}

/*
 * Created with IntelliJ IDEA.
 * User: gonztobi
 * Date: 10/2/13
 * Time: 4:12 PM
 */
class Spinner(initModel: SpinnerModel) extends Component {
  override lazy val peer = new JSpinner(initModel) with SuperMixin
  def this() = this(new SpinnerNumberModel())

  def value = peer.getValue
  def value_=(newValue: Any) { peer.setValue(newValue) }
  def editor = peer.getEditor
  def editor_=(newEditor: Component) { peer.setEditor(newEditor.peer) }
  def commit() = peer.commitEdit()
  def model = peer.getModel
  def model_=(newModel: SpinnerModel) { peer.setModel(newModel) }
  def nextValue = peer.getNextValue
  def prevValue = peer.getPreviousValue

  peer.addChangeListener(scala.swing.Swing.ChangeListener {
    e => publish(new ValueChanged(this))
  })
}


text:
<?php

/**
 * @author Adriaan Knapen <a.d.knapen@protonmail.com>
 * @date 3-3-2017
 */
abstract class MenuFrame extends CI_Controller
{
    private $ci;

    public function __construct($group) {
        $this->ci = get_instance();
        $this->group = $group;
    }

    public function getMenu() {
        $menuElements = $this->menuElements();

        return $this->buildMenu($menuElements, 0);
    }

    private function buildMenu($elements, $level) {
        if (is_array($elements)) {
            $html = '';
            $title = null;
            $icon = null;

            foreach ($elements as $key => $element) {
                if ($key === 0 && !is_array($element) && get_class($element) == MenuItem::class) {
                    /** @var MenuItem $element */
                    $title = $element->getTitle();
                    $icon = $element->getIcon();
                } else {
                    $html .= $this->buildMenu($element, $level + 1);
                }
            }

            return $this->getSubMenuHtml($title, $icon, $html, $level);
        } else {
            return $this->buildListItem($elements);
        }
    }

    /**
     * @param MenuItem $menuItem
     * @return string
     */
    private function buildListItem($menuItem) {
        // If this is a page, check if the user has the rights to even visit it, else hide it.
        if (get_class($menuItem) == MenuPage::class) {
            /** @var MenuPage $menuItem*/
            $pageClass = $menuItem->getPage();

            require_once(APPPATH.'pages/'.$this->group.'/'.$pageClass.'.php');

            /** @var PageFrame $page */
            $page = new $pageClass(['group' => $this->group], false);

            if (!$page->hasAccess()) {
                return '';
            }
        }

        $title = $menuItem->getTitle();
        $link = $this->getLink($menuItem);
        $icon = $menuItem->getIcon();

        return $this->getListItemHtml($title, $link, $icon) . "\n";
    }

    abstract function getListItemHtml($title, $link, $icon);

    abstract function getSubMenuHtml($title, $icon, $content, $level);

    private function getLink($menuItem) {
        switch (get_class($menuItem)) {
            case MenuLink::class:
                /** @var MenuLink $menuItem */
                return $menuItem->getLink();
            case MenuPage::class:
                /** @var MenuPage $menuItem */
                $page = $menuItem->getPage();
                $pageName = substr($page, 0, -strlen('Page'));

                $pageParams = $menuItem->getParams();
                if (empty($pageParams)) {
                    $linkParams = '';
                } else {
                    $linkParams = '/' . implode('/', $pageParams);
                }

                return site_url($this->group . '/' . $pageName . $linkParams);
            case MenuItem::class:
                return null;
            default:
                throw new Exception('Invalid menu item parsed.');
        }
    }

    protected  abstract function menuElements();
}

class MenuItem {
    protected $title;
    protected $icon;

    public function __construct($title, $icon = null) {
        $this->title = $title;
        $this->icon = $icon;
    }

    public function setIcon($icon) {
        $this->icon = $icon;
    }

    public function getTitle() {
        return $this->title;
    }

    public function getIcon() {
        return $this->icon;
    }
}

class MenuLink extends MenuItem {
    protected $link;

    public function __construct($title, $link, $icon = null)
    {
        parent::__construct($title, $icon);

        $this->link = $link;
    }

    public function setLink($link) {
        $this->link = $link;
    }

    public function getLink() {
        return $this->link;
    }
}

class MenuPage extends MenuItem {
    protected $page;
    protected $params;

    public function __construct($title, $page, $icon = null, $params = []) {
        parent::__construct($title, $icon);

        $this->page = $page;
        $this->params = $params;
    }

    public function setPage($page) {
        $this->page = $page;
    }

    public function getPage() {
        return $this->page;
    }

    public function getParams() {
        return $this->params;
    }
}


text:
$LOAD_PATH << File.expand_path('../../lib' , __FILE__)
require 'wolfbot'

Thread.abort_on_exception = true

channel = Wolfbot::Twitch.new
channel.listen

while (channel.running)
  command = gets.chomp

  command =='quit' ? channel.stop : channel.send(command)
end
puts 'Exited.'