text:
extern pthread_mutex_t thread_pool_wait_lock;
extern unsigned int    thread_pool_cnt;
extern pthread_cond_t  thread_pool_cond;

// Increments available thread counter. Called at the end of each thread.
#define THREAD_POOL_DONE() \
pthread_mutex_lock(&thread_pool_wait_lock); \
thread_pool_cnt++; \
pthread_cond_signal(&thread_pool_cond); \
pthread_mutex_unlock(&thread_pool_wait_lock);

// Inititializes thread pool
#define THREAD_POOL_INIT() \
  pthread_mutex_t thread_pool_wait_lock; \
  unsigned int    thread_pool_cnt = 4; \
  pthread_cond_t  thread_pool_cond;

// Sets available threads
#define THREAD_POOL_SET(number) { thread_pool_cnt = number; };

// Waits until threads are available and decrements available thread counter.
#define THREAD_POOL_WAIT() \
pthread_mutex_lock(&thread_pool_wait_lock); \
while(thread_pool_cnt <= 0) { \
  pthread_cond_wait(&thread_pool_cond, &thread_pool_wait_lock); \
} \
thread_pool_cnt--; \
pthread_mutex_unlock(&thread_pool_wait_lock);

#else // __THREAD_POOL
// No thread pool support. Always starts new thread
#define THREAD_JOIN(arg) pthread_join(arg, NULL);
#define THREAD_POOL_WAIT()
#define THREAD_POOL_INIT()
#define THREAD_POOL_DONE()
#endif

#define THREAD_RUN2(thread_name, function) \
THREAD_POOL_WAIT() \
  void NAME(__pthread_wrapper)(void) {\
  do {function();} while(0); \
  THREAD_POOL_DONE(); \
}; \
pthread_create(&thread_name, NULL, (void*)NAME(__pthread_wrapper), NULL);

#define THREAD_RUN3(thread_name, function, arg1) \
THREAD_POOL_WAIT() \
typedef struct { \
  __typeof__(arg1)* _arg1; \
} NAME(__pthread_struct); \
void NAME(__pthread_wrapper)(NAME(__pthread_struct)* data) {\
  do {function(*data->_arg1);} while(0); \
  THREAD_POOL_DONE(); \
}; \
NAME(__pthread_struct) NAME(__data); \
NAME(__data)._arg1 = &arg1; \
pthread_create(&thread_name, NULL, (void*)NAME(__pthread_wrapper), &NAME(__data));

#define THREAD_RUN4(thread_name, function, arg1, arg2) \
THREAD_POOL_WAIT() \
typedef struct { \
  __typeof__(arg1)* _arg1; \
  __typeof__(arg2)* _arg2; \
} NAME(__pthread_struct); \
void NAME(__pthread_wrapper)(NAME(__pthread_struct)* data) {\
  do {function(*data->_arg1, *data->_arg2);} while(0); \
  THREAD_POOL_DONE(); \
}; \
NAME(__pthread_struct) NAME(__data); \
NAME(__data)._arg1 = &arg1; \
NAME(__data)._arg2 = &arg2; \
pthread_create(&thread_name, NULL, (void*)NAME(__pthread_wrapper), &NAME(__data));

#define THREAD_RUN5(thread_name, function, arg1, arg2, arg3) \
THREAD_POOL_WAIT() \
typedef struct { \
  __typeof__(arg1)* _arg1; \
  __typeof__(arg2)* _arg2; \
  __typeof__(arg3)* _arg3; \
} NAME(__pthread_struct); \
void NAME(__pthread_wrapper)(NAME(__pthread_struct)* data) {\
  do {function(*data->_arg1, *data->_arg2, *data->_arg3);} while(0); \
  THREAD_POOL_DONE(); \
}; \
NAME(__pthread_struct) NAME(__data); \
NAME(__data)._arg1 = &arg1; \
NAME(__data)._arg2 = &arg2; \
NAME(__data)._arg3 = &arg3; \
pthread_create(&thread_name, NULL, (void*)NAME(__pthread_wrapper), &NAME(__data));

#define THREAD_RUN6(thread_name, function, arg1, arg2, arg3, arg4) \
THREAD_POOL_WAIT() \
typedef struct { \
  __typeof__(arg1)* _arg1; \
  __typeof__(arg2)* _arg2; \
  __typeof__(arg3)* _arg3; \
  __typeof__(arg4)* _arg4; \
} NAME(__pthread_struct); \
void NAME(__pthread_wrapper)(NAME(__pthread_struct)* data) {\
  do {function(*data->_arg1, *data->_arg2, *data->_arg3, *data->_arg4);} while(0); \
  THREAD_POOL_DONE(); \
}; \
NAME(__pthread_struct) NAME(__data); \
NAME(__data)._arg1 = &arg1; \
NAME(__data)._arg2 = &arg2; \
NAME(__data)._arg3 = &arg3; \
NAME(__data)._arg4 = &arg4; \
pthread_create(&thread_name, NULL, (void*)NAME(__pthread_wrapper), &NAME(__data));

#define THREAD_RUN7(thread_name, function, arg1, arg2, arg3, arg4, arg5) \
THREAD_POOL_WAIT() \
typedef struct { \
  __typeof__(arg1)* _arg1; \
  __typeof__(arg2)* _arg2; \
  __typeof__(arg3)* _arg3; \
  __typeof__(arg4)* _arg4; \
  __typeof__(arg5)* _arg5; \
} NAME(__pthread_struct); \
void NAME(__pthread_wrapper)(NAME(__pthread_struct)* data) {\
  do {function(*data->_arg1, *data->_arg2, *data->_arg3, *data->_arg4, *data->_arg5);} while(0); \
  THREAD_POOL_DONE(); \
}; \
NAME(__pthread_struct) NAME(__data); \
NAME(__data)._arg1 = &arg1; \
NAME(__data)._arg2 = &arg2; \
NAME(__data)._arg3 = &arg3; \
NAME(__data)._arg4 = &arg4; \
NAME(__data)._arg5 = &arg5; \
pthread_create(&thread_name, NULL, (void*)NAME(__pthread_wrapper), &NAME(__data));

#define THREAD_RUN8(thread_name, function, arg1, arg2, arg3, arg4, arg5, arg6) \
THREAD_POOL_WAIT() \
typedef struct { \
  __typeof__(arg1)* _arg1; \
  __typeof__(arg2)* _arg2; \
  __typeof__(arg3)* _arg3; \
  __typeof__(arg4)* _arg4; \
  __typeof__(arg5)* _arg5; \
  __typeof__(arg6)* _arg6; \
} NAME(__pthread_struct); \
void NAME(__pthread_wrapper)(NAME(__pthread_struct)* data) {\
  do {function(*data->_arg1, *data->_arg2, *data->_arg3, *data->_arg4, *data->_arg5, *data->arg6);} while(0); \
  THREAD_POOL_DONE(); \
}; \
NAME(__pthread_struct) NAME(__data); \
NAME(__data)._arg1 = &arg1; \
NAME(__data)._arg2 = &arg2; \
NAME(__data)._arg3 = &arg3; \
NAME(__data)._arg4 = &arg4; \
NAME(__data)._arg5 = &arg5; \
NAME(__data)._arg6 = &arg6; \
pthread_create(&thread_name, NULL, (void*)NAME(__pthread_wrapper), &NAME(__data));


text:
<!doctype html>

    <meta charset="utf-8">

    <title>Introduction to Machine Learning and Data Mining</title>

    <meta name="description" content="Introduction to Machine Learning and Data Mining">
    <meta name="author" content="Kyle I S Harrington">

    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">

    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, minimal-ui">

    <link rel="stylesheet" href="css/reveal.css">
    <link rel="stylesheet" href="css/theme/black_KISHtufts135_2016.css" id="theme">

    <link rel="stylesheet" href="lib/css/zenburn.css">

	Tufts University - COMP 135 - Spring 2016 / Kyle I S Harrington

Introduction to Machine Learning and Data Mining

	     Kyle I S Harrington / kyle@eecs.tufts.edu

Some slides adapted from Roni Khardon, Andrew Moore, Mohand Said Allili, David Sontag, Frank Dellaert, Michael Jordan, Yair Weiss

    ## Logistics

    Make up class: May 5?

    Quiz 2 moved to 04/12

    Midterm Questions

    [Early handwriting recognition](http://jackschaedler.github.io/handwriting-recognition/)

      ## Limitations of K-means

      K-means has limitations for some data.

      ![K-means fails to separate 2 clusters](images/kmeans_k=2_incorrect.svg)

      What do we do?

      ## Probabilistic Membership

      We could assign cluster labels probabilistically using distance.

      $p(x \in \textbf{cluster i}) = \frac{ d(x,C_i) }{ \displaystyle \sum^{k}_j d(x,C_j) }$

      where $d(x,C_i)$ is the distance from instance x to centroid of cluster i.

      ##  Probabilistic Membership

      ![Ambiguity of K-means clear from distance map](images/kmeans_k=2_incorrect_dists.svg)

      Problem solved?

      ## Distribution Approximation

      - We have a set of samples that were drawn from some unknown distribution.

      - What if we want to know the probability that a sample came from a distribution?

      - We need to know or approximate the underlying distribution.

      ## Gaussian

      We know Gaussian's from 1D:

      $f(\mu,\sigma) = \frac{1}{\sigma \sqrt{2 \pi}}  e^{ -\frac{1}{2} ( \frac{x-\mu}{\sigma})^2}$

      ![Example 1D Gaussian. mean = 0, std = 1](images/example_gaussian_1D.svg)

      ## Gaussian Mixture Models

      Most distributions don't look like a single Gaussian.

      Use multiple Gaussians to describe a distribution.

      A Gaussian mixture model uses k-Gaussians, each with a weight, mean, and the entire model uses a covariance matrix.

      ## Gaussian Mixture Models

      - k Gaussians
      - mixing weights for each Gaussian
      - mean for each Gaussian
      - covariance matrix

      ## Gaussian Mixture Models

      GMM can be written as

      $N(x | \mu, \Sigma) = \frac{e^{-1/2(x - \mu)^T \Sigma^{-1} (x - \mu)}}{(2 \pi)^{d/2} \sqrt{ |\Sigma| }}$

      ## Gaussian Mixture Models

      - Covariance matrix describes the shape of the gaussian in each direction

      ## Gaussian Mixture Models

      Spherical covariance: 1 variance for all Gaussians

      ![GMM spherical covariance matrix](images/em_k=2_cov_spherical.svg)

      ## Gaussian Mixture Models

      Diagonal covariance: 1 variance for each Gaussian

      ![GMM spherical covariance matrix](images/em_k=2_cov_diag.svg)

      ## Gaussian Mixture Models

      Full covariance: variance is dependent on all dimensions for all dimensions

      ![GMM spherical covariance matrix](images/em_k=2_cov_full.svg)

      ## Gaussian Mixture Models

      GMMs can generative!

      Pick Gaussian $k$ with probability $w_k$, and generate a point from the corresponding Gaussian

Gaussian mixture model

Given some data $D$ drawn from an unknown distribution

Estimate the parameters $\theta$ of a GMM that fits the data

How do we find the Gaussian parameters?

Flipping coins

2 coins, A and B, with bias to land on heads: $\theta_A$ and $\theta_B$

Repeat for $i$ = 1 to 5:

Randomly choose a coin, store as class label $z_i$

['b', 'b', 'a', 'a', 'b']

Flip the coin 10 times, store number of heads as $x_i$

[4, 8, 4, 4, 7]

Flipping coins

We can calculate the bias from these observations directly:

$\dot{\theta}_A = \frac{ \textit{# heads using A}}{ \textit{# flips using A}}$

$\dot{\theta}_A = \frac{8}{20}$

$\dot{\theta}_B = \frac{ \textit{# heads using B}}{ \textit{# flips using B}}$

$\dot{\theta}_B = \frac{19}{30}$

This information was recorded as # heads in $x$ and coin identifier in $z$

What if we didn't have $z$?

Flipping coins

What if we didn't have $z$ (the coin flipped to produce a certain # of heads)?

$z$ is now a "hidden", "latent" variable

How do we find $\theta_A$ and $\theta_B$?

    ## Flipping coins

    Start with initial estimates $\dot{\theta} = ( \dot{\theta}_A^{(0)}$, $\dot{\theta}_B^{(0)} )$

    For each set of 10 coin flips, where we know the # of heads as $x_i$

    i.e. [4, 8, 4, 4, 7]

    - Determine which coin was most likely using $\dot{\theta}^{(t)}$
    - Assume these were the coins that generated the data, and use maximum likelihood to update $\dot{\theta}^{(t+1)}$

    Repeat until convergence

Maximum Likelihood Estimation

We know $x_1$, $x_2$, ..., $x_R$ which follow some $N( \mu, \sigma^2 )$

How do we find $\mu$ (assume we know $\sigma^2$)?

Maximum Likelihood Estimation

We know $x_1$, $x_2$, ..., $x_R$ which follow some $N( \mu, \sigma^2 )$

How do we find $\mu$ (assume we know $\sigma^2$)?

Maximum Likelihood Estimation: For which $\mu$ is $x_1, x_2, ... x_R$ most likely?

Maximum a posteriori: Which $\mu$ maximizes $p(\mu | x_1, x_2, ... x_R, \sigma^2 )$?

Expectation-maximization

Expectation-Maximization (EM) algorithm is an approach to maximize likelihood

Expectation-maximization

Iterate:

E-Step: Estimate the distribution given the data and current parameters

M-Step: Maximize the distribution

    ## Expectation-maximization

    Expectation step: Calculate the expected log likelihood, $E[log L(\Theta | X,Z)]$

    $E[L( \Theta^{(t)} | X, Z )] = p(X|\Theta^{(t)}) = \displaystyle \sum_Z p(X,Z | \Theta^{(t)})$

    ## Expectation-maximization

    Maximization step: Find the parameters that maximize the log likelihood

    $\Theta^{(t+1)} = argmax_{\Theta} E[log L(\Theta | X,Z)]$

Expectation-maximization

Initialization:

Mean of data + random offset

Use K-means to get a good initialization

Expectation-maximization

Termination:

Maximum number of iterations

Threshold change in log-likelihood

Threshold change in parameters

Expectation-maximization

Limitations

Prone to local maxima

Numerical stability of covariance matrix (add noise to stabilize)

    ## Choosing number of components

    Can use Bayesian Information Criterion to score GMMs

    $BIC = -2 ln( L(\Theta | X ) ) + k \cdot ln( n )$

    where $L$ is the likelihood, $k$ is the degrees of freedom (number of free parameters), and $n$ is the number of datapoints.

    ## EM Example

    Step 1

    ![Step 1 of EM](images/em_k=2_cov_full_step=1.svg)

    ## EM Example

    Step 2

    ![Step 2 of EM](images/em_k=2_cov_full_step=2.svg)

    ## EM Example

    Step 3

    ![Step 3 of EM](images/em_k=2_cov_full_step=3.svg)

    ## EM Example

    Step 4

    ![Step 4 of EM](images/em_k=2_cov_full_step=4.svg)

What Next?

Guest Lecture on Aggregation

redpajama_set_name: RedPajamaGithub


text:
package net.sf.esfinge.gamification.mechanics;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import net.sf.esfinge.gamification.achievement.Achievement;
import net.sf.esfinge.gamification.event.BonusBuilder;
import net.sf.esfinge.gamification.event.annotation.EventListenerImplementation;
import net.sf.esfinge.gamification.event.annotation.GamificationListener;
import net.sf.esfinge.gamification.event.listener.EventListener;
import net.sf.esfinge.gamification.listener.AchievementListener;
import net.sf.esfinge.gamification.listener.EvaluationAchievementProcessorAchievementoListener;

public abstract class Game {

	 public abstract void insertAchievement(Object user, Achievement a);

	 public abstract void deleteAchievement(Object user, Achievement a);

	 public abstract void updateAchievement(Object user, Achievement a);

	 public abstract Achievement getAchievement(Object user, String
	 achievName);

	 public abstract Map<String, Achievement> getAchievements(Object user);

	// /
	private List<AchievementListener> listeners = new ArrayList<>();

	/*
	 * (non-Javadoc)
	 *
	 * @see
	 * net.sf.esfinge.gamification.mechanics.Game#addAchievement(java.lang.Object,
	 * net.sf.esfinge.gamification.achievement.Achievement)
	 */
	public void addAchievement(Object user, Achievement a) {
		Achievement p = this.getAchievement(user, a.getName());
		if (p == null){
			this.insertAchievement(user, a);
		}else{
			p.incrementAchievement(a);
			this.updateAchievement(user, p);
		}
		notifyAdded(user, a);
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see
	 * net.sf.esfinge.gamification.mechanics.Game#removeAchievement(java.lang.Object
	 * , net.sf.esfinge.gamification.achievement.Achievement)
	 */
	public void removeAchievement(Object user, Achievement a) {
		Achievement p = this.getAchievement(user, a.getName());
		if (p.removeAchievement(a))
			this.deleteAchievement(user, p);
		else
			this.updateAchievement(user, p);
		notifyRemoved(user, a);
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see
	 * net.sf.esfinge.gamification.mechanics.Game#addListener(net.sf.esfinge.gamification
	 * .listener.AchievementListener)
	 */
	public void addListener(AchievementListener listener) {
		listeners.add(listener);
	}

	private void notifyAdded(Object user, Achievement a) {
		for (AchievementListener l : listeners) {
			l.achievementAdded(this, user, a);

		}
	}

	private void notifyRemoved(Object user, Achievement a) {
		for (AchievementListener l : listeners) {
			l.achievementRemoved(this, user, a);

		}
	}

	public BonusBuilder addBonus(Achievement bonus) {
		return new BonusBuilder(this, bonus);
	}

	public void addEventListeners(Object... configurationObjects){
		for (Object configurationObject : configurationObjects) {
			Class<?> configurationObjectClazz = configurationObject.getClass();
			if(configurationObjectClazz.isAnnotationPresent(GamificationListener.class)){
				for(Method m: configurationObjectClazz.getDeclaredMethods()){
					for(Annotation an: m.getAnnotations()){
						if(an.annotationType().isAnnotationPresent(EventListenerImplementation.class)){
							try {
								EventListenerImplementation eventImplementation = an.annotationType().getAnnotation(EventListenerImplementation.class);
								EventListener eventListener = eventImplementation.value().newInstance();
								eventListener.setAnnotation(an);
								eventListener.setMethod(m);
								eventListener.setConfigurationObject(configurationObject);
								this.addListener(new EvaluationAchievementProcessorAchievementoListener(eventListener));
							} catch (Exception e) {
								//adicionando o listener de Eventos com anotações
							}
						}
					}
				}
			}
		}
	}

}


text:
using namespace Platform;
using namespace Windows::Foundation::Metadata;

namespace libfilter
{
    public ref class Filter sealed
    {
    public:
		// Create a filter with an initial impulseResponse of [0 0 0 0 0 0 0 0]
        Filter(const Array<float>^ impulseResponse);

		// Clean everything up, releasing all internally created buffers, etc...
		virtual ~Filter();

		// Feed one new sample into the filter, return the new sample of output
		float filter( float data );

		// Convolve every sample in the input array, returning the array of new output samples
		// Don't worry about the [DefaultOverload] thing, it's just to squash a warning
		[DefaultOverload] Array<float>^ filter( const Array<float>^ data );

		// Return our internal impulseResponse
		Array<float>^ getImpulseResponse();

		// Update our internal impulseResponse
		//void updateImpulseResponse( const Platform::Array<float>^ impulseResponse );
	private:
		float *impulseResponse, *prevData;
		unsigned int idx;
		unsigned int N;
	};
}


text:
__author__ = 'frank'

from zstacklib.utils import plugin
from zstacklib.utils import log
from zstacklib.utils import jsonobject
from zstacklib.utils import http
from zstacklib.utils import shell
from zstacklib.utils import linux
from zstacklib.utils import lock
import cherrypy
from iscsifilesystemagent import  iscsiagent
import time
import os

logger = log.get_logger(__name__)

class AgentCapacityResponse(object):
    def __init__(self):
        self.success = True
        self.error = ''
        self.availableCapacity = None
        self.totalCapacity = None

class InitRsp(AgentCapacityResponse):
    def __abs__(self):
        super(InitRsp, self).__init__()

class DownloadBitsFromSftpBackupStorageRsp(AgentCapacityResponse):
    def __abs__(self):
        super(DownloadBitsFromSftpBackupStorageRsp, self).__init__()

class CheckBitsExistenceRsp(object):
    def __init__(self):
        self.isExisting = True

class DeleteBitsRsp(AgentCapacityResponse):
    def __init__(self):
        super(DeleteBitsRsp, self).__init__()

class CreateRootVolumeFromTemplateRsp(AgentCapacityResponse):
    def __init__(self):
        super(CreateRootVolumeFromTemplateRsp, self).__init__()
        self.iscsiPath = None

class CreateEmptyVolumeRsp(AgentCapacityResponse):
    def __init__(self):
        super(CreateEmptyVolumeRsp, self).__init__()
        self.iscsiPath = None

class UploadToSftpRsp(AgentCapacityResponse):
    def __init__(self):
        super(UploadToSftpRsp, self).__init__()

class CreateIscsiTargetRsp(AgentCapacityResponse):
    def __init__(self):
        super(CreateIscsiTargetRsp, self).__init__()
        self.target = None
        self.lun = None

class CreateSubVolumeRsp(AgentCapacityResponse):
    def __init__(self):
        super(CreateSubVolumeRsp, self).__init__()
        self.path = None
        self.size = None

class CreateSymlinkRsp(AgentCapacityResponse):
    def __init__(self):
        super(CreateSymlinkRsp, self).__init__()

class DeleteSymlinkRsp(AgentCapacityResponse):
    def __init__(self):
        super(DeleteSymlinkRsp, self).__init__()

@lock.lock('tgt-admin-update')
def update_target(target_name):
    shell.call('tgt-admin --update %s --force' % target_name)

class BtrfsPlugin(plugin.Plugin):
    TYPE = "btrfs"
    INIT_PATH = "/%s/init" % TYPE
    DOWNLOAD_FROM_SFTP_PATH = "/%s/image/sftp/download" % TYPE
    CHECK_BITS_EXISTENCE = "/%s/bits/checkifexists" % TYPE
    DELETE_BITS_EXISTENCE = "/%s/bits/delete" % TYPE
    CREATE_ROOT_VOLUME_PATH = "/%s/volumes/createrootfromtemplate" % TYPE
    CREATE_EMPTY_VOLUME_PATH = "/%s/volumes/createempty" % TYPE
    UPLOAD_TO_SFTP = "/%s/bits/upload" % TYPE
    CREATE_TARGET_PATH = "/%s/target/create" % TYPE
    DELETE_TARGET_PATH = "/%s/target/delete" % TYPE
    DELETE_SUBVOLUME_PATH = "/%s/subvolume/delete" % TYPE
    CREATE_SUBVOLUME_PATH = "/%s/subvolume/create" % TYPE
    GET_CAPACITY_PATH = "/%s/capacity/get" % TYPE

    def _get_disk_capacity(self):
        total = linux.get_total_disk_size(self.root)

        out = shell.call('df')
        avail = None
        for l in out.split('\n'):
            if self.root in l:
                _, _, _, avail, _, _ = l.split()

        if not avail:
            raise Exception('cannot find available capacity, "df" output":\n %s' % out)

        return total, long(avail) * 1024

    @iscsiagent.replyerror
    def init(self, req):
        cmd = jsonobject.loads(req[http.REQUEST_BODY])
        rsp = InitRsp()

        def check():
            out = shell.call('mount')
            for l in out.split('\n'):
                if 'btrfs' in l and cmd.rootFolderPath in l:
                    return

            raise Exception('%s is not mounted as btrfs in system' % cmd.rootFolderPath)

        check()
        self.root = cmd.rootFolderPath
        rsp.totalCapacity, rsp.availableCapacity = self._get_disk_capacity()
        return jsonobject.dumps(rsp)

    @iscsiagent.replyerror
    def download_from_sftp(self, req):
        cmd = jsonobject.loads(req[http.REQUEST_BODY])
        rsp = DownloadBitsFromSftpBackupStorageRsp()
        sub_vol_dir = os.path.dirname(cmd.primaryStorageInstallPath)
        if not os.path.exists(sub_vol_dir):
            parent_dir = os.path.dirname(sub_vol_dir)
            shell.call('mkdir -p %s' % parent_dir)
            shell.call('btrfs subvolume create %s' % sub_vol_dir)

        linux.scp_download(cmd.hostname, cmd.sshKey, cmd.backupStorageInstallPath, cmd.primaryStorageInstallPath)

        def get_image_format():
            out = shell.call('qemu-img info %s' % cmd.primaryStorageInstallPath)
            for l in out.split('\n'):
                if 'file format' in l:
                    _, f = l.split(':')
                    return f.strip()
            raise Exception('cannot get image format of %s, qemu-img info outputs:\n%s\n' % (cmd.primaryStorageInstallPath, out))

        f = get_image_format()
        if 'qcow2' in f:
            shell.call('/usr/bin/qemu-img convert -f qcow2 -O raw %s %s.img' % (cmd.primaryStorageInstallPath, cmd.primaryStorageInstallPath))
            shell.call('mv %s.img %s' % (cmd.primaryStorageInstallPath, cmd.primaryStorageInstallPath))
        elif 'raw' in f:
            pass
        else:
            raise Exception('unsupported image format[%s] of %s' % (f, cmd.primaryStorageInstallPath))

        rsp.totalCapacity, rsp.availableCapacity = self._get_disk_capacity()
        logger.debug('downloaded %s:%s to %s' % (cmd.hostname, cmd.backupStorageInstallPath, cmd.primaryStorageInstallPath))
        return jsonobject.dumps(rsp)

    @iscsiagent.replyerror
    def check_bits(self, req):
        cmd = jsonobject.loads(req[http.REQUEST_BODY])
        rsp = CheckBitsExistenceRsp()
        rsp.isExisting = os.path.exists(cmd.path)
        return jsonobject.dumps(rsp)

    def _delete_target(self, target_name, conf_uuid):
        conf_file = os.path.join('/etc/tgt/conf.d/%s.conf' % conf_uuid)
        shell.call('rm -f %s' % conf_file)

        output = shell.call('tgt-admin --show')
        if target_name not in output:
            return

        update_target(target_name)

    @iscsiagent.replyerror
    def delete_bits(self, req):
        cmd = jsonobject.loads(req[http.REQUEST_BODY])
        rsp = DeleteBitsRsp()

        if cmd.volumeUuid:
            iscsi_path = cmd.iscsiPath
            target_name = iscsi_path.lstrip('iscsi://').split('/')[1]
            self._delete_target(target_name, cmd.volumeUuid)

        sub_vol_dir = os.path.dirname(cmd.installPath)
        shell.call('btrfs subvolume delete %s' % sub_vol_dir)
        rsp.totalCapacity, rsp.availableCapacity = self._get_disk_capacity()
        logger.debug('deleted %s' % cmd.installPath)
        return jsonobject.dumps(rsp)

    def _create_iscsi_target(self, vol_uuid, install_path, chapUsername=None, chapPassword=None):
        target_name = "iqn.%s.org.zstack:%s" % (time.strftime('%Y-%m'), vol_uuid)

        if not os.path.exists(install_path):
            raise Exception('unable to create iscsi target, file %s not found' % install_path)

        VOLUME_CONF = """\
<target %s>
backing-store %s
driver iscsi
write-cache on
</target>
"""

        VOLUME_CONF_WITH_CHAP_AUTH = """\
<target %s>
    backing-store %s
    driver iscsi
    %s
    write-cache on
</target>
"""

        if chapUsername and chapPassword:
            conf = VOLUME_CONF_WITH_CHAP_AUTH % (target_name, install_path, "incominguser %s %s" % (chapUsername, chapPassword))
        else:
            conf = VOLUME_CONF % (target_name, install_path)

        conf_dir = '/etc/tgt/conf.d'
        shell.call('mkdir -p %s' % conf_dir)

        conf_file = os.path.join(conf_dir, '%s.conf' % vol_uuid)
        if os.path.exists(conf_file):
            with open(conf_file, 'r') as fd:
                current_conf = fd.read()
                if current_conf == conf:
                    return target_name, conf_file

        with open(conf_file, 'w') as fd:
            fd.write(conf)

        return target_name, conf_file

    @iscsiagent.replyerror
    def create_root_volume(self, req):
        cmd = jsonobject.loads(req[http.REQUEST_BODY])
        rsp = CreateRootVolumeFromTemplateRsp()

        if not os.path.exists(cmd.templatePathInCache):
            raise Exception('cannot find template[%s] in cache' % cmd.templatePathInCache)

        template_sub_vol = os.path.dirname(cmd.templatePathInCache)
        root_volume_sub_vol = os.path.dirname(cmd.installPath)
        parent_root_volume_sub_vol = os.path.dirname(root_volume_sub_vol)
        shell.call('mkdir -p %s' % parent_root_volume_sub_vol)
        shell.call('btrfs subvolume snapshot %s %s' % (template_sub_vol, root_volume_sub_vol))
        src_vol_name = os.path.join(root_volume_sub_vol, os.path.basename(cmd.templatePathInCache))
        if src_vol_name != cmd.installPath:
            shell.call('mv %s %s' % (src_vol_name, cmd.installPath))

        target_name, conf_file = self._create_iscsi_target(cmd.volumeUuid, cmd.installPath, cmd.chapUsername, cmd.chapPassword)
        update_target(target_name)

        rsp.totalCapacity, rsp.availableCapacity = self._get_disk_capacity()
        rsp.iscsiPath = target_name

        logger.debug('create root volume[path:%s, iscsi target: %s, iscsi conf: %s]' % (cmd.installPath, target_name, conf_file))
        return jsonobject.dumps(rsp)

    def _create_subvolume(self, src, dst):
        src_volume = os.path.dirname(src)
        shell.call('mkdir -p %s' % os.path.dirname(dst))
        shell.call('btrfs subvolume snapshot %s %s' % (src_volume, dst))
        src_file_name = os.path.basename(src)
        dst_path = os.path.join(dst, src_file_name)
        return dst_path

    @iscsiagent.replyerror
    def create_subvolume(self, req):
        cmd = jsonobject.loads(req[http.REQUEST_BODY])
        rsp = CreateSubVolumeRsp()
        if os.path.exists(cmd.dst):
            raise Exception('subvolume[%s] existing' % cmd.dst)

        rsp.path = self._create_subvolume(cmd.src, cmd.dst)
        rsp.size = os.path.getsize(rsp.path)
        rsp.totalCapacity, rsp.availableCapacity = self._get_disk_capacity()
        logger.debug('created subvolume[%s]' % cmd.dst)
        return jsonobject.dumps(rsp)

    @iscsiagent.replyerror
    def create_empty_volume(self, req):
        cmd = jsonobject.loads(req[http.REQUEST_BODY])
        rsp = CreateEmptyVolumeRsp()

        sub_vol_path = os.path.dirname(cmd.installPath)
        if os.path.exists(sub_vol_path):
            raise Exception('cannot create empty volume; %s already exists' % sub_vol_path)

        parent_dir = os.path.dirname(sub_vol_path)
        shell.call('mkdir -p %s' % parent_dir)
        shell.call('btrfs subvolume create %s' % sub_vol_path)

        linux.raw_create(cmd.installPath, cmd.size)
        target_name, conf_file = self._create_iscsi_target(cmd.volumeUuid, cmd.installPath, cmd.chapUsername, cmd.chapPassword)
        update_target(target_name)

        rsp.iscsiPath = target_name
        rsp.totalCapacity, rsp.availableCapacity = self._get_disk_capacity()

        logger.debug('created empty volume[path:%s, iscsi target:%s, iscsi conf:%s]' % (cmd.installPath, target_name, conf_file))
        return jsonobject.dumps(rsp)

    @iscsiagent.replyerror
    def upload_to_sftp(self, req):
        cmd = jsonobject.loads(req[http.REQUEST_BODY])
        rsp = UploadToSftpRsp()

        if not os.path.exists(cmd.primaryStorageInstallPath):
            raise Exception('cannot find %s' % cmd.primaryStorageInstallPath)

        linux.scp_upload(cmd.backupStorageHostName, cmd.backupStorageSshKey, cmd.primaryStorageInstallPath, cmd.backupStorageInstallPath)

        logger.debug('uploaded %s to sftp backup storage[hostname: %s, path:%s]' % (cmd.primaryStorageInstallPath, cmd.backupStorageHostName, cmd.backupStorageInstallPath))
        return jsonobject.dumps(rsp)

    @iscsiagent.replyerror
    def create_target(self, req):
        cmd = jsonobject.loads(req[http.REQUEST_BODY])
        rsp = CreateIscsiTargetRsp()

        target_name, conf_file = self._create_iscsi_target(cmd.volumeUuid, cmd.installPath, cmd.chapUsername, cmd.chapPassword)
        update_target(target_name)

        rsp.target = target_name
        rsp.lun = 1
        logger.debug('created ISCSI target[%s] in conf file[%s]' % (target_name, conf_file))
        return jsonobject.dumps(rsp)

    @iscsiagent.replyerror
    def delete_target(self, req):
        cmd = jsonobject.loads(req[http.REQUEST_BODY])
        self._delete_target(cmd.target, cmd.uuid)
        logger.debug('deleted iscsi target[%s]' % cmd.target)
        rsp = AgentCapacityResponse()
        return jsonobject.dumps(rsp)

    @iscsiagent.replyerror
    def get_capacity(self, req):
        rsp = AgentCapacityResponse()
        rsp.totalCapacity, rsp.availableCapacity = self._get_disk_capacity()
        return jsonobject.dumps(rsp)

    def start(self):
        self.root = None

        http_server = self.config.http_server
        http_server.register_async_uri(self.INIT_PATH, self.init)
        http_server.register_async_uri(self.DOWNLOAD_FROM_SFTP_PATH, self.download_from_sftp)
        http_server.register_async_uri(self.CHECK_BITS_EXISTENCE, self.check_bits)
        http_server.register_async_uri(self.DELETE_BITS_EXISTENCE, self.delete_bits)
        http_server.register_async_uri(self.CREATE_ROOT_VOLUME_PATH, self.create_root_volume)
        http_server.register_async_uri(self.CREATE_EMPTY_VOLUME_PATH, self.create_empty_volume)
        http_server.register_async_uri(self.UPLOAD_TO_SFTP, self.upload_to_sftp)
        http_server.register_async_uri(self.CREATE_TARGET_PATH, self.create_target)
        http_server.register_async_uri(self.DELETE_TARGET_PATH, self.delete_target)
        http_server.register_async_uri(self.CREATE_SUBVOLUME_PATH, self.create_subvolume)
        http_server.register_async_uri(self.GET_CAPACITY_PATH, self.get_capacity)

    def stop(self):
        pass


text:
<?php
/**
 * Moscow Exchange ISS Client
 *
 * @link      http://github.com/panychek/moex
 * @license   http://www.opensource.org/licenses/mit-license.php MIT
 * @author    Igor Panychek panychek@gmail.com
 */

namespace Panychek\MoEx\Exception;

class BadMethodCallException extends \BadMethodCallException implements ExceptionInterface
{
}


text:
package io.netty.handler.codec.http.websocketx.extensions.compression;

import static io.netty.handler.codec.http.websocketx.extensions.compression.
        PerMessageDeflateServerExtensionHandshaker.*;
import static org.junit.Assert.*;
import io.netty.handler.codec.http.websocketx.extensions.WebSocketServerExtension;
import io.netty.handler.codec.http.websocketx.extensions.WebSocketExtensionData;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

import org.junit.Test;

public class PerMessageDeflateServerExtensionHandshakerTest {

    @Test
    public void testNormalHandshake() {
        WebSocketServerExtension extension;
        WebSocketExtensionData data;
        Map<String, String> parameters;

        // initialize
        PerMessageDeflateServerExtensionHandshaker handshaker =
                new PerMessageDeflateServerExtensionHandshaker();

        // execute
        extension = handshaker.handshakeExtension(
                new WebSocketExtensionData(PERMESSAGE_DEFLATE_EXTENSION, Collections.emptyMap()));

        // test
        assertNotNull(extension);
        assertEquals(WebSocketServerExtension.RSV1, extension.rsv());
        assertTrue(extension.newExtensionDecoder() instanceof PerMessageDeflateDecoder);
        assertTrue(extension.newExtensionEncoder() instanceof PerMessageDeflateEncoder);

        // execute
        data = extension.newResponseData();

        assertEquals(PERMESSAGE_DEFLATE_EXTENSION, data.name());
        assertTrue(data.parameters().isEmpty());

        // initialize
        parameters = new HashMap<>();
        parameters.put(CLIENT_MAX_WINDOW, null);
        parameters.put(CLIENT_NO_CONTEXT, null);

        // execute
        extension = handshaker.handshakeExtension(
                new WebSocketExtensionData(PERMESSAGE_DEFLATE_EXTENSION, Collections.emptyMap()));

        // test
        assertNotNull(extension);
        assertEquals(WebSocketServerExtension.RSV1, extension.rsv());
        assertTrue(extension.newExtensionDecoder() instanceof PerMessageDeflateDecoder);
        assertTrue(extension.newExtensionEncoder() instanceof PerMessageDeflateEncoder);

        // execute
        data = extension.newResponseData();

        // test
        assertEquals(PERMESSAGE_DEFLATE_EXTENSION, data.name());
        assertTrue(data.parameters().isEmpty());

        // initialize
        parameters = new HashMap<>();
        parameters.put(SERVER_MAX_WINDOW, "12");
        parameters.put(SERVER_NO_CONTEXT, null);

        // execute
        extension = handshaker.handshakeExtension(
                new WebSocketExtensionData(PERMESSAGE_DEFLATE_EXTENSION, parameters));

        // test
        assertNull(extension);
    }

    @Test
    public void testCustomHandshake() {
        WebSocketServerExtension extension;
        Map<String, String> parameters;
        WebSocketExtensionData data;

        // initialize
        PerMessageDeflateServerExtensionHandshaker handshaker =
                new PerMessageDeflateServerExtensionHandshaker(6, true, 10, true, true);

        parameters = new HashMap<>();
        parameters.put(CLIENT_MAX_WINDOW, null);
        parameters.put(SERVER_MAX_WINDOW, "12");
        parameters.put(CLIENT_NO_CONTEXT, null);
        parameters.put(SERVER_NO_CONTEXT, null);

        // execute
        extension = handshaker.handshakeExtension(
                new WebSocketExtensionData(PERMESSAGE_DEFLATE_EXTENSION, parameters));

        // test
        assertNotNull(extension);
        assertEquals(WebSocketServerExtension.RSV1, extension.rsv());
        assertTrue(extension.newExtensionDecoder() instanceof PerMessageDeflateDecoder);
        assertTrue(extension.newExtensionEncoder() instanceof PerMessageDeflateEncoder);

        // execute
        data = extension.newResponseData();

        // test
        assertEquals(PERMESSAGE_DEFLATE_EXTENSION, data.name());
        assertTrue(data.parameters().containsKey(CLIENT_MAX_WINDOW));
        assertEquals("10", data.parameters().get(CLIENT_MAX_WINDOW));
        assertTrue(data.parameters().containsKey(SERVER_MAX_WINDOW));
        assertEquals("12", data.parameters().get(SERVER_MAX_WINDOW));
        assertTrue(data.parameters().containsKey(CLIENT_MAX_WINDOW));
        assertTrue(data.parameters().containsKey(SERVER_MAX_WINDOW));

        // initialize
        parameters = new HashMap<>();
        parameters.put(SERVER_MAX_WINDOW, "12");
        parameters.put(SERVER_NO_CONTEXT, null);

        // execute
        extension = handshaker.handshakeExtension(
                new WebSocketExtensionData(PERMESSAGE_DEFLATE_EXTENSION, parameters));

        // test
        assertNotNull(extension);
        assertEquals(WebSocketServerExtension.RSV1, extension.rsv());
        assertTrue(extension.newExtensionDecoder() instanceof PerMessageDeflateDecoder);
        assertTrue(extension.newExtensionEncoder() instanceof PerMessageDeflateEncoder);

        // execute
        data = extension.newResponseData();

        // test
        assertEquals(PERMESSAGE_DEFLATE_EXTENSION, data.name());
        assertEquals(2, data.parameters().size());
        assertTrue(data.parameters().containsKey(SERVER_MAX_WINDOW));
        assertEquals("12", data.parameters().get(SERVER_MAX_WINDOW));
        assertTrue(data.parameters().containsKey(SERVER_NO_CONTEXT));

        // initialize
        parameters = new HashMap<>();

        // execute
        extension = handshaker.handshakeExtension(
                new WebSocketExtensionData(PERMESSAGE_DEFLATE_EXTENSION, parameters));
        // test
        assertNotNull(extension);

        // execute
        data = extension.newResponseData();

        // test
        assertEquals(PERMESSAGE_DEFLATE_EXTENSION, data.name());
        assertTrue(data.parameters().isEmpty());
    }
}


text:
class GameStateManager
{
private:
	std::stack<GameState*> states;

public:
	GameStateManager(void);
	~GameStateManager(void);

	void init();
	void shutdown();

	void update();
	void render();

};


text:
#include "tensorflow/core/kernels/cwise_ops_common.h"

namespace tensorflow {
REGISTER8(UnaryOp, CPU, "Abs", functor::abs, Eigen::half, bfloat16, float,
          double, int8, int16, int32, int64);
REGISTER2(UnaryOp, CPU, "ComplexAbs", functor::abs, complex64, complex128);

#if GOOGLE_CUDA || TENSORFLOW_USE_ROCM
#ifndef MLIR_GENERATED_GPU_KERNELS_ENABLED
REGISTER4(UnaryOp, GPU, "Abs", functor::abs, Eigen::half, float, double, int64);
#endif
REGISTER2(UnaryOp, GPU, "ComplexAbs", functor::abs, complex64, complex128);

// A special GPU kernel for int32.
// TODO(b/25387198): Also enable int32 in device memory. This kernel
// registration requires all int32 inputs and outputs to be in host memory.
#ifndef MLIR_GENERATED_GPU_KERNELS_ENABLED
REGISTER_KERNEL_BUILDER(Name("Abs")
                            .Device(DEVICE_GPU)
                            .HostMemory("x")
                            .HostMemory("y")
                            .TypeConstraint<int32>("T"),
                        UnaryOp<CPUDevice, functor::abs<int32>>);
#endif
#endif

}  // namespace tensorflow


text:
package org.camunda.demo.dmnTest.RugbyRules;

import org.apache.ibatis.logging.LogFactory;
import org.camunda.bpm.engine.impl.util.LogUtil;
import org.camunda.bpm.engine.test.ProcessEngineRule;
import org.camunda.bpm.engine.test.Deployment;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;

import static org.camunda.bpm.engine.test.assertions.ProcessEngineTests.*;
import static org.junit.Assert.*;

/**
 * Test case starting an in-memory database-backed Process Engine.
 */
public class InMemoryH2Test {

  @Rule
  public ProcessEngineRule rule = new ProcessEngineRule();

  private static final String PROCESS_DEFINITION_KEY = "RugbyRules";

  // enable more detailed logging
  static {
//    LogUtil.readJavaUtilLoggingConfigFromClasspath(); // process engine
//    LogFactory.useJdkLogging(); // MyBatis
  }

  @Before
  public void setup() {
    init(rule.getProcessEngine());
  }

  /**
   * Just tests if the process definition is deployable.
  @Test
  @Deployment(resources = "process.bpmn")
  public void testParsingAndDeployment() {
    // nothing is done here, as we just want to check for exceptions during deployment
  }*/

}


text:
var path = require('path');
var format = require('util').format;

exports.init = function(grunt) {
  var ast = require('cmd-util').ast;
  var iduri = require('cmd-util').iduri;

  var exports = {};

  exports.html2jsParser = function(fileObj, options) {
    // don't transport debug html files
    if (/\-debug\.html/.test(fileObj.src)) return;
    grunt.log.writeln('Transport ' + fileObj.src + ' -> ' + fileObj.dest);
    // transport html to js
    var data = fileObj.srcData || grunt.file.read(fileObj.src);
    var id = options.idleading + fileObj.name.replace(/\.js$/, '');

    data = html2js(data, id);
    data = ast.getAst(data).print_to_string(options.uglify);
    var dest = fileObj.dest + '.js';
    grunt.file.write(dest, data);

    if (!options.debug) {
      return;
    }
    dest = dest.replace(/\.html\.js$/, '-debug.html.js');
    grunt.log.writeln('Creating debug file: ' + dest);

    data = ast.modify(data, function(v) {
      var ext = path.extname(v);
      if (ext && options.parsers[ext]) {
        return v.replace(new RegExp('\\' + ext + '$'), '-debug' + ext);
      } else {
        return v + '-debug';
      }
    });
    data = data.print_to_string(options.uglify);
    grunt.file.write(dest, data);
  };

  return exports;
};

// helpers
function html2js(code, id) {
  var tpl = 'define("%s", [], "%s");';

  code = code.split(/\r\n|\r|\n/).map(function(line) {
    return line.replace(/\\/g, '\\\\');
  }).join('\n');

  code = format(tpl, id, code.replace(/\"/g, '\\\"'));
  return code;
}

exports.html2js = html2js;


text:
module Text.Parsec.String
    ( Parser, GenParser, parseFromFile
    ) where

import Text.Parsec.Error
import Text.Parsec.Prim

type Parser = Parsec String ()
type GenParser tok st = Parsec [tok] st

-- | @parseFromFile p filePath@ runs a string parser @p@ on the
-- input read from @filePath@ using 'Prelude.readFile'. Returns either a 'ParseError'
-- ('Left') or a value of type @a@ ('Right').
--
-- >  main    = do{ result <- parseFromFile numbers "digits.txt"
-- >              ; case result of
-- >                  Left err  -> print err
-- >                  Right xs  -> print (sum xs)
-- >              }
parseFromFile :: Parser a -> String -> IO (Either ParseError a)
parseFromFile p fname
    = do input <- readFile fname
         return (runP p () fname input)


text:
[![Gem Version](https://badge.fury.io/rb/dmm-api.png)](http://badge.fury.io/rb/dmm-api)
Ruby DMM Web Service API ver 2.0

## Installation

Add this line to your application's Gemfile:

    gem 'dmm-api'

And then execute:

    $ bundle

Or install it yourself as:

    $ gem install dmm-api

## Usage

```ruby
require 'dmm/api'

# configure
Dmm::Api.configure do |options|
  options[:api_id] = "your api id"
  options[:affiliate_id] = "id-001,id-002,id-003" # your affiliate id multiple choice
  options[:site] = "DMM.com or DMM.co.jp"
  ...
end

# dmm web service api 2.0
res = Dmm::Api.get({:service => 'lod',:floor => 'nmb48',:keyword => "山本彩"})
res.code # 200
res.message # "OK"
res["result"][0]["items"][0]["item"].each do |v|
  title = v["title"][0]
  ...
end
```

See the [examples directory](https://github.com/shoprev/dmm-api/tree/master/example) for more usage.

Refer to [DMM Web API documentation](https://affiliate.dmm.com/api/guide/) for more infomation.

## Contributing

1. Fork it
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Commit your changes (`git commit -am 'Add some feature'`)
4. Push to the branch (`git push origin my-new-feature`)
5. Create new Pull Request


text:
(* Mathematica package *)

CreatePalette[
	Column[
		{
			Button["Needs[\"MTools`\"]",Needs["MTools`"], Appearance -> "Palette"]
			,
			Button[Defer[InterpretSymbol[\[SelectionPlaceholder]]], Inherited, BaseStyle -> "Evaluate", Evaluator -> None, Appearance -> "Palette"]
			,
			Button[Defer[UninterpretSymbol[\[SelectionPlaceholder]]], Inherited, BaseStyle -> "Evaluate", Evaluator -> None, Appearance -> "Palette"]
		}
	]
	,
	WindowTitle -> "MTools"
]


text:
package org.jaxen.function;

import java.util.List;

import org.jaxen.Context;
import org.jaxen.Function;
import org.jaxen.FunctionCallException;
import org.jaxen.Navigator;

/**
 *
4.4 number floor(number)

 *
 *
 *

 * The floor function returns the largest (closest to positive infinity)
 * number that is not greater than the argument and that is an integer....
 * If the argument is NaN, then NaN is returned.
 * If the argument is positive infinity, then positive infinity is returned.
 * If the argument is negative infinity, then negative infinity is returned.
 * If the argument is positive zero, then positive zero is returned.
 * If the argument is negative zero, then negative zero is returned.
 * If the argument is greater than zero, but less than 1, then positive zero is returned.
 *

 *
 * @author bob mcwhirter (bob @ werken.com)
 *
 * @see Section 4.4 of the XPath Specification
 * @see XPath Errata
 */
public class FloorFunction implements Function
{

    /**
     * Create a new FloorFunction object.
     */
    public FloorFunction() {}

    /** Returns the largest integer less than or equal to a number.
     *
     * @param context the context at the point in the
     *         expression when the function is called
     * @param args a list with exactly one item which will be converted to a
     *     Double as if by the XPath number() function
     *
     * @return a Double containing the largest integer less than or equal
     *     to args.get(0)
     *
     * @throws FunctionCallException if args has more or less than one item
     */
    public Object call(Context context,
                       List args) throws FunctionCallException
    {
        if (args.size() == 1)
        {
            return evaluate( args.get(0),
                             context.getNavigator() );
        }

        throw new FunctionCallException( "floor() requires one argument." );
    }

    /** Returns the largest integer less than or equal to the argument.
     * If necessary, the argument is first converted to a Double
     * as if by the XPath number() function.
     *
     * @param obj the object whose floor is returned
     * @param nav ignored
     *
     * @return a Double containing the largest integer less
     *     than or equal to obj
     */
    public static Double evaluate(Object obj,
                                  Navigator nav)
    {
        Double value = NumberFunction.evaluate( obj,
                                                nav );

        return new Double( Math.floor( value.doubleValue() ) );
    }
}


text:
var old = $.fn.bootgrid;

$.fn.bootgrid = function (option)
{
    var args = Array.prototype.slice.call(arguments, 1),
        returnValue = null,
        elements = this.each(function (index)
        {
            var $this = $(this),
                instance = $this.data(namespace),
                options = typeof option === "object" && option;

            if (!instance && option === "destroy")
            {
                return;
            }
            if (!instance)
            {
                $this.data(namespace, (instance = new Grid(this, options)));
                init.call(instance);
            }
            if (typeof option === "string")
            {
                if (option.indexOf("get") === 0 && index === 0)
                {
                    returnValue = instance[option].apply(instance, args);
                }
                else if (option.indexOf("get") !== 0)
                {
                    return instance[option].apply(instance, args);
                }
            }
        });
    return (typeof option === "string" && option.indexOf("get") === 0) ? returnValue : elements;
};

$.fn.bootgrid.Constructor = Grid;

// GRID NO CONFLICT
// ===============

$.fn.bootgrid.noConflict = function ()
{
    $.fn.bootgrid = old;
    return this;
};

// GRID DATA-API
// ============

$("[data-toggle=\"bootgrid\"]").bootgrid();


text:
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.

using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
using System.Web.Http;
using System.Web.Http.Controllers;
using Microsoft.AspNet.WebHooks.Properties;
using Newtonsoft.Json.Linq;

namespace Microsoft.AspNet.WebHooks
{
    /// <summary>
    /// Provides an abstract <see cref="IWebHookReceiver"/> implementation which can be used to base other implementations on.
    /// </summary>
    public abstract class WebHookReceiver : IWebHookReceiver
    {
        internal const string CodeQueryParameter = "code";

        /// <summary>
        /// Initializes a new instance of the <see cref="WebHookReceiver"/> class.
        /// </summary>
        protected WebHookReceiver()
        {
        }

        /// <inheritdoc />
        public abstract IEnumerable<string> Names { get; }

        /// <inheritdoc />
        public abstract Task<HttpResponseMessage> ReceiveAsync(string receiver, HttpRequestContext context, HttpRequestMessage request);

        /// <summary>
        /// Provides a time consistent comparison of two secrets in the form of two byte arrays.
        /// </summary>
        /// <param name="inputA">The first secret to compare.</param>
        /// <param name="inputB">The second secret to compare.</param>
        /// <returns>Returns <c>true</c> if the two secrets are equal, <c>false</c> otherwise.</returns>
        [MethodImpl(MethodImplOptions.NoOptimization)]
        protected internal static bool SecretEqual(byte[] inputA, byte[] inputB)
        {
            if (ReferenceEquals(inputA, inputB))
            {
                return true;
            }

            if (inputA == null || inputB == null || inputA.Length != inputB.Length)
            {
                return false;
            }

            bool areSame = true;
            for (int i = 0; i < inputA.Length; i++)
            {
                areSame &= inputA[i] == inputB[i];
            }
            return areSame;
        }

        /// <summary>
        /// Provides a time consistent comparison of two secrets in the form of two strings.
        /// </summary>
        /// <param name="inputA">The first secret to compare.</param>
        /// <param name="inputB">The second secret to compare.</param>
        /// <returns>Returns <c>true</c> if the two secrets are equal, <c>false</c> otherwise.</returns>
        [MethodImpl(MethodImplOptions.NoOptimization)]
        protected internal static bool SecretEqual(string inputA, string inputB)
        {
            if (ReferenceEquals(inputA, inputB))
            {
                return true;
            }

            if (inputA == null || inputB == null || inputA.Length != inputB.Length)
            {
                return false;
            }

            bool areSame = true;
            for (int i = 0; i < inputA.Length; i++)
            {
                areSame &= inputA[i] == inputB[i];
            }
            return areSame;
        }

        /// <summary>
        /// Some WebHooks rely on HTTPS for sending WebHook requests in a secure manner. A <see cref="WebHookReceiver"/>
        /// can call this method to ensure that the incoming WebHook request is using HTTPS. If the request is not
        /// using HTTPS an error will be generated and the request will not be further processed.
        /// </summary>
        /// <remarks>This method does allow local HTTP requests using <c>localhost</c>.</remarks>
        /// <param name="request">The current <see cref="HttpRequestMessage"/>.</param>
        [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "Disposed by caller.")]
        protected virtual void EnsureSecureConnection(HttpRequestMessage request)
        {
            if (request == null)
            {
                throw new ArgumentNullException("request");
            }

            if (!request.IsLocal() && !request.RequestUri.IsHttps())
            {
                string msg = string.Format(CultureInfo.CurrentCulture, ReceiverResources.Receiver_NoHttps, GetType().Name, Uri.UriSchemeHttps);
                request.GetConfiguration().DependencyResolver.GetLogger().Error(msg);
                HttpResponseMessage noHttps = request.CreateErrorResponse(HttpStatusCode.BadRequest, msg);
                throw new HttpResponseException(noHttps);
            }
        }

        /// <summary>
        /// For WebHooks providers with insufficient security considerations, the receiver can require that the WebHook URI must
        /// be an <c>https</c> URI and contain a 'code' query parameter with a value configured in the application setting with the name
        /// <paramref name="setting"/>.
        /// A sample WebHook URI is '<c>https://<host>/api/webhooks/incoming/<receiver>?code=c2e25cd9-6f63-44f6-bf2a-729bcc9f236a</c>'.
        /// The 'code' parameter must be between 32 and 64 characters long.
        /// </summary>
        /// <param name="request">The current <see cref="HttpRequestMessage"/>.</param>
        /// <param name="setting">The name of the application setting containing the expected 'code' query parameter value.</param>
        [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "Response is disposed by Web API.")]
        protected virtual void EnsureValidCode(HttpRequestMessage request, string setting)
        {
            if (request == null)
            {
                throw new ArgumentNullException("request");
            }

            EnsureSecureConnection(request);

            NameValueCollection queryParameters = request.RequestUri.ParseQueryString();
            string code = queryParameters[CodeQueryParameter];
            if (string.IsNullOrEmpty(code))
            {
                string msg = string.Format(CultureInfo.CurrentCulture, ReceiverResources.Receiver_NoCode, CodeQueryParameter);
                request.GetConfiguration().DependencyResolver.GetLogger().Error(msg);
                HttpResponseMessage noCode = request.CreateErrorResponse(HttpStatusCode.BadRequest, msg);
                throw new HttpResponseException(noCode);
            }

            string secretKey = GetWebHookSecret(request, setting, 32, 64);
            if (!WebHookReceiver.SecretEqual(code, secretKey))
            {
                string msg = string.Format(CultureInfo.CurrentCulture, ReceiverResources.Receiver_BadCode, CodeQueryParameter);
                request.GetConfiguration().DependencyResolver.GetLogger().Error(msg);
                HttpResponseMessage invalidCode = request.CreateErrorResponse(HttpStatusCode.BadRequest, msg);
                throw new HttpResponseException(invalidCode);
            }
        }

        /// <summary>
        /// Gets the locally configured WebHook secret key used to validate any signature header provided in a WebHook request.
        /// </summary>
        /// <param name="request">The current <see cref="HttpRequestMessage"/>.</param>
        /// <param name="setting">The name of the application setting to look for.</param>
        /// <param name="minLength">The minimum length of the key value.</param>
        /// <param name="maxLength">The maximum length of the key value.</param>
        [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "Disposed by caller")]
        protected virtual string GetWebHookSecret(HttpRequestMessage request, string setting, int minLength, int maxLength)
        {
            if (request == null)
            {
                throw new ArgumentNullException("request");
            }

            HttpConfiguration config = request.GetConfiguration();
            string secret = config.DependencyResolver.GetSettings().GetValueOrDefault(setting);
            if (secret == null || secret.Length < minLength || secret.Length > maxLength)
            {
                string msg = string.Format(CultureInfo.CurrentCulture, ReceiverResources.Receiver_BadSecret, setting, minLength, maxLength);
                config.DependencyResolver.GetLogger().Error(msg);
                HttpResponseMessage noSecret = request.CreateErrorResponse(HttpStatusCode.InternalServerError, msg);
                throw new HttpResponseException(noSecret);
            }
            return secret;
        }

        /// <summary>
        /// Gets the value of a given HTTP request header field. If the field is either not present or has more than one value
        /// then an error is generated.
        /// </summary>
        /// <param name="request">The current <see cref="HttpRequestMessage"/>.</param>
        /// <param name="requestHeaderName">The name of the HTTP request header to look up.</param>
        /// <returns>The signature header.</returns>
        [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "Disposed by caller")]
        protected virtual string GetRequestHeader(HttpRequestMessage request, string requestHeaderName)
        {
            if (request == null)
            {
                throw new ArgumentNullException("request");
            }

            IEnumerable<string> headers;
            if (!request.Headers.TryGetValues(requestHeaderName, out headers) || headers.Count() != 1)
            {
                int headersCount = headers != null ? headers.Count() : 0;
                string msg = string.Format(CultureInfo.CurrentCulture, ReceiverResources.Receiver_BadHeader, requestHeaderName, headersCount);
                request.GetConfiguration().DependencyResolver.GetLogger().Info(msg);
                HttpResponseMessage noHeader = request.CreateErrorResponse(HttpStatusCode.BadRequest, msg);
                throw new HttpResponseException(noHeader);
            }

            return headers.First();
        }

        /// <summary>
        /// Reads the JSON HTTP request entity body.
        /// </summary>
        /// <param name="request">The current <see cref="HttpRequestMessage"/>.</param>
        /// <returns>A <see cref="JObject"/> containing the HTTP request entity body.</returns>
        protected virtual async Task<JObject> ReadAsJsonAsync(HttpRequestMessage request)
        {
            // Check that there is a request body
            if (request.Content == null)
            {
                string msg = ReceiverResources.Receiver_NoBody;
                request.GetConfiguration().DependencyResolver.GetLogger().Info(msg);
                HttpResponseMessage noBody = request.CreateErrorResponse(HttpStatusCode.BadRequest, msg);
                throw new HttpResponseException(noBody);
            }

            // Check that the request body is JSON
            if (!request.Content.IsJson())
            {
                string msg = ReceiverResources.Receiver_NoJson;
                request.GetConfiguration().DependencyResolver.GetLogger().Info(msg);
                HttpResponseMessage noJson = request.CreateErrorResponse(HttpStatusCode.UnsupportedMediaType, msg);
                throw new HttpResponseException(noJson);
            }

            try
            {
                // Read request body
                JObject result = await request.Content.ReadAsAsync<JObject>();
                return result;
            }
            catch (Exception ex)
            {
                string msg = ReceiverResources.Receiver_BadJson;
                request.GetConfiguration().DependencyResolver.GetLogger().Error(msg, ex);
                HttpResponseMessage invalidBody = request.CreateErrorResponse(HttpStatusCode.BadRequest, msg, ex);
                throw new HttpResponseException(invalidBody);
            }
        }

        /// <summary>
        /// Reads the HTML Form Data HTTP request entity body.
        /// </summary>
        /// <param name="request">The current <see cref="HttpRequestMessage"/>.</param>
        /// <returns>A <see cref="NameValueCollection"/> containing the HTTP request entity body.</returns>
        protected virtual async Task<NameValueCollection> ReadAsFormDataAsync(HttpRequestMessage request)
        {
            // Check that there is a request body
            if (request.Content == null)
            {
                string msg = ReceiverResources.Receiver_NoBody;
                request.GetConfiguration().DependencyResolver.GetLogger().Info(msg);
                HttpResponseMessage noBody = request.CreateErrorResponse(HttpStatusCode.BadRequest, msg);
                throw new HttpResponseException(noBody);
            }

            // Check that the request body is form data
            if (!request.Content.IsFormData())
            {
                string msg = ReceiverResources.Receiver_NoFormData;
                request.GetConfiguration().DependencyResolver.GetLogger().Info(msg);
                HttpResponseMessage noJson = request.CreateErrorResponse(HttpStatusCode.UnsupportedMediaType, msg);
                throw new HttpResponseException(noJson);
            }

            try
            {
                // Read request body
                NameValueCollection result = await request.Content.ReadAsFormDataAsync();
                return result;
            }
            catch (Exception ex)
            {
                string msg = ReceiverResources.Receiver_BadFormData;
                request.GetConfiguration().DependencyResolver.GetLogger().Error(msg, ex);
                HttpResponseMessage invalidBody = request.CreateErrorResponse(HttpStatusCode.BadRequest, msg, ex);
                throw new HttpResponseException(invalidBody);
            }
        }

        /// <summary>
        ///  Creates a 405 "Method Not Allowed" response which a receiver can use to indicate that a request with a
        ///  non-support HTTP method could not be processed.
        /// </summary>
        /// <param name="request">The current <see cref="HttpRequestMessage"/>.</param>
        /// <returns>A fully initialized "Method Not Allowed" <see cref="HttpResponseMessage"/>.</returns>
        [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "Disposed by caller")]
        protected virtual HttpResponseMessage CreateBadMethodResponse(HttpRequestMessage request)
        {
            if (request == null)
            {
                throw new ArgumentNullException("request");
            }

            string msg = string.Format(CultureInfo.CurrentCulture, ReceiverResources.Receiver_BadMethod, request.Method, GetType().Name);
            request.GetConfiguration().DependencyResolver.GetLogger().Error(msg);
            HttpResponseMessage badMethod = request.CreateErrorResponse(HttpStatusCode.MethodNotAllowed, msg);
            return badMethod;
        }

        /// <summary>
        ///  Creates a 400 "Bad Request" response which a receiver can use to indicate that a request had an invalid signature
        ///  and as a result could not be processed.
        /// </summary>
        /// <param name="request">The current <see cref="HttpRequestMessage"/>.</param>
        /// <param name="signatureHeaderName">The name of the HTTP header with invalid contents.</param>
        /// <returns>A fully initialized "Bad Request" <see cref="HttpResponseMessage"/>.</returns>
        [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "Disposed by caller")]
        protected virtual HttpResponseMessage CreateBadSignatureResponse(HttpRequestMessage request, string signatureHeaderName)
        {
            if (request == null)
            {
                throw new ArgumentNullException("request");
            }

            string msg = string.Format(CultureInfo.CurrentCulture, ReceiverResources.Receiver_BadSignature, signatureHeaderName, GetType().Name);
            request.GetConfiguration().DependencyResolver.GetLogger().Error(msg);
            HttpResponseMessage badSignature = request.CreateErrorResponse(HttpStatusCode.BadRequest, msg);
            return badSignature;
        }

        /// <summary>
        /// Processes the WebHook request by calling all registered <see cref="IWebHookHandler"/> instances.
        /// </summary>
        /// <param name="receiver">The case-insensitive name of the receiver used by the incoming WebHook. The receiver
        /// name can for example be <c>dropbox</c> or <c>github</c>.</param>
        /// <param name="context">The <see cref="HttpRequestContext"/> for this WebHook invocation.</param>
        /// <param name="request">The <see cref="HttpRequestMessage"/> for this WebHook invocation.</param>
        /// <param name="actions">The collection of actions associated with this WebHook invocation.</param>
        /// <param name="data">Optional data associated with this WebHook invocation.</param>
        protected virtual async Task<HttpResponseMessage> ExecuteWebHookAsync(string receiver, HttpRequestContext context, HttpRequestMessage request, IEnumerable<string> actions, object data)
        {
            if (receiver == null)
            {
                throw new ArgumentNullException("receiver");
            }
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }
            if (request == null)
            {
                throw new ArgumentNullException("request");
            }
            if (actions == null)
            {
                actions = new string[0];
            }

            // Execute handlers. Note that we wait for them to complete before
            // we return. This means that we don't send back the final response
            // before all handlers have executed. As a result we expect handlers
            // to be fairly quick in what they process. If a handler sets the
            // Response property on the context then the execution is stopped
            // and that response returned. If a handler throws an exception then
            // the execution of handlers is also stopped.
            WebHookHandlerContext handlerContext = new WebHookHandlerContext(actions)
            {
                Data = data,
                Request = request,
                RequestContext = context,
            };

            receiver = receiver.ToLowerInvariant();
            IEnumerable<IWebHookHandler> handlers = context.Configuration.DependencyResolver.GetHandlers();
            foreach (IWebHookHandler handler in handlers)
            {
                // Only call handlers with matching receiver name (or no receiver name in which case they support all receivers)
                if (handler.Receiver != null && !string.Equals(receiver, handler.Receiver, StringComparison.OrdinalIgnoreCase))
                {
                    continue;
                }

                await handler.ExecuteAsync(receiver, handlerContext);

                // Check if response has been set and if so stop the processing.
                if (handlerContext.Response != null)
                {
                    return handlerContext.Response;
                }
            }
            return request.CreateResponse();
        }
    }
}


text:
package main

import (
	"encoding/json"
	"errors"
	"flag"
	"fmt"
	"log"
	"net/http"
	"os"
	"regexp"
	"sort"
	"strconv"
	"strings"
	"sync"
	"time"

	"github.com/mattn/go-runewidth"
	"github.com/nsf/termbox-go"
)

const TIMEOUT = time.Duration(time.Second * 10)                                   // how long to wait on a call
const URL = "http://finance.yahoo.com/webservice/v1/symbols/%s/quote?format=json" // where we're getting our data from
const UP = "↑"                                                                    // rune 8593
const DOWN = "↓"                                                                  // rune 8595

var re = regexp.MustCompile(`^\d.+\.\d{2}`) // this is to have only 2 decimal places
var signalChan = make(chan os.Signal, 1)    // channel to catch ctrl-c

// Flag variables to hold CLI arguments
var (
	symbolFlag   = flag.String("s", "", "Symbols for ticker, comma seperate (no spaces)")
	intervalFlag = flag.Int("i", 1, "Interval for stock data to be updated in seconds")
)

// Stock is the top level of the returned JSON
type Stock struct {
	List List `json:"list"`
}

// List hold the metadata and list of returned symbol data
type List struct {
	Meta      Meta        `json:"meta"`
	Resources []Resources `json:"resources"`
}

// Meta is the calls metadata
type Meta struct {
	Type  string `json:"type"`
	Start uint   `json:"start"`
	Count uint   `json:"count"`
}

// Resources holds a JSON obj with the symbol data
type Resources struct {
	Resource Resource `json:"resource"`
}

// Resource contains the actual JSON obj with the symbol data
type Resource struct {
	Classname string `json:"classname"`
	Fields    Fields `json:"fields"`
}

// Fields holds all of the retrieved data from the API call
type Fields struct {
	Name    string `json:"name"`    // name of company
	Price   string `json:"price"`   // current price
	Symbol  string `json:"symbol"`  // stock symbol
	TS      string `json:"ts"`      //
	Type    string `json:"type"`    // type of stock (equity, etc...)
	UTCTime string `json:"utctime"` // time in UTC
	Volume  string `json:"volume"`  // shares traded
}

// stockwatcher holds the relevant data for the running instance
type stockwatcher struct {
	quotes   map[string]map[string]float64
	interval time.Duration
	m        *sync.Mutex
}

// NewStockWatcher returns a new instance of stockwatcher with the given parameters
func NewStockWatcher(i time.Duration) *stockwatcher {
	return &stockwatcher{
		quotes:   make(map[string]map[string]float64),
		interval: i,
		m:        &sync.Mutex{},
	}
}

// add takes the given symbol and populates a key in the quotes map
func (t *stockwatcher) add(symbol string) {
	t.m.Lock()
	defer t.m.Unlock()
	if _, ok := t.quotes[symbol]; !ok {
		t.quotes[symbol] = map[string]float64{}
	}
}

// updateStock populates stockwatcher struct with stock prices
func (t *stockwatcher) updateStock(symbol string, price float64) {
	t.m.Lock()
	defer t.m.Unlock()
	t.quotes[symbol] = map[string]float64{
		"previous": t.quotes[symbol]["current"],
		"current":  price,
	}
}

// query will retrieve data for a given symbol
func query(symbol string) (*Stock, error) {
	data := &Stock{}
	client := http.Client{
		Timeout: TIMEOUT,
	}

	resp, err := client.Get(fmt.Sprintf(URL, symbol))
	if err != nil {
		return nil, errors.New("unable to retrive symbol data")
	}
	defer resp.Body.Close()

	if err := json.NewDecoder(resp.Body).Decode(&data); err != nil {
		log.Fatalln(err)
	}
	return data, nil
}

// convertPrice converts the given string to a float64 value
func convertPrice(p string) float64 {
	price, err := strconv.ParseFloat(p, 64)
	if err != nil {
		log.Fatalln(err)
		os.Exit(1)
	}
	return price
}

// runner goes through and gets the data for each symbol
func (t *stockwatcher) runner() {
	var wg sync.WaitGroup
	for k, _ := range t.quotes {
		wg.Add(1)
		go func(k string) {
			defer wg.Done()
			stock, err := query(k)
			if err != nil { // if we can't get a response from the API, put 0.00's in and keep going
				t.updateStock(k, 0.00)
				return
			}
			t.updateStock(stock.List.Resources[0].Resource.Fields.Symbol,
				convertPrice(re.FindString(stock.List.Resources[0].Resource.Fields.Price)),
			)
		}(k)
	}
	wg.Wait()
}

// formatData formats the given data for printing
func (t *stockwatcher) formatData() {
	// populate list with keys from quote map
	var keys []string
	for k := range t.quotes {
		keys = append(keys, k)
	}
	sort.Strings(keys) // alphabetize keys

	pos := 1
	for _, k := range keys {
		// print format for first run or if not change detected from previous run
		if t.quotes[k]["previous"] == 0.00 || t.quotes[k]["previous"] == t.quotes[k]["current"] {
			printTb(1,
				pos,
				fmt.Sprintf("%-6s %-7v %11s %-4s\n", k, t.quotes[k]["current"], "%", "-"),
				termbox.ColorWhite, termbox.ColorDefault,
			)
			pos++
			// print format in green if current price being is greater than previous price
		} else if t.quotes[k]["current"] > t.quotes[k]["previous"] {
			printTb(1,
				pos,
				fmt.Sprintf("%-6s %-7v +%-.6f %% %-4s\n", k, t.quotes[k]["current"], t.quotes[k]["current"]/t.quotes[k]["previous"], UP),
				termbox.ColorGreen,
				termbox.ColorDefault,
			)
			pos++
			// print format in red if current price being is lesser than previous price
		} else {
			printTb(1,
				pos,
				fmt.Sprintf("%-6s %-7v -%-.6f %% %-4s\n", k, t.quotes[k]["current"], t.quotes[k]["current"]/t.quotes[k]["previous"], DOWN),
				termbox.ColorRed,
				termbox.ColorDefault,
			)
			pos++
		}
	}
}

// printTb prints the given data out to the screen
func printTb(x, y int, msg string, fg, bg termbox.Attribute) {
	for _, c := range []rune(msg) {
		termbox.SetCell(x, y, c, fg, bg)
		x += runewidth.RuneWidth(c)
	}
	termbox.Flush()
}

func main() {
	flag.Parse()

	// make sure we got what was expected from the CLI
	if flag.NFlag() != 2 || *symbolFlag == "" {
		flag.Usage()
		os.Exit(1)
	}

	t := NewStockWatcher(time.Duration(*intervalFlag) * time.Second)

	// check if more than one symbol has been given
	switch {
	case strings.Contains(*symbolFlag, ","):
		for _, a := range strings.Split(*symbolFlag, ",") {
			t.add(a)
		}
	default:
		t.add(*symbolFlag)
	}

	// initialize termbox
	err := termbox.Init()
	if err != nil {
		log.Fatal(err)
	}
	termbox.Clear(termbox.ColorDefault, termbox.ColorDefault)

	event := make(chan termbox.Event)
	go func() {
		for {
			// Post events to channel
			event <- termbox.PollEvent()
		}
	}()

loop:
	for {
		t.runner()
		t.formatData()

		// Poll key event or timeout (maybe)
		select {
		case <-event:
			break loop
		case <-time.After(t.interval):
			continue loop
		}
	}
	close(event)
	time.Sleep(1 * time.Second)
	termbox.Close()
	os.Exit(0) // close out on a good note
}


text:
package org.knowm.xchange.utils.nonce;

import java.util.concurrent.atomic.AtomicLong;

import si.mazi.rescu.SynchronizedValueFactory;

public class AtomicLongIncrementalTime2013NonceFactory implements SynchronizedValueFactory<Long> {

  private static final long START_MILLIS = 1356998400000L; // Jan 1st, 2013 in milliseconds from epoch

  //counter for the nonce
  private final AtomicLong lastNonce = new AtomicLong((System.currentTimeMillis() - START_MILLIS) / 250L);

  @Override
  public Long createValue() {

    return lastNonce.incrementAndGet();

  }
}


text:
import { createTestStoryUrl } from './storybook-helpers';
import { browser } from 'protractor';
import { waitForVisibilityOf } from 'wix-ui-test-utils/protractor';

export const navigateToTestUrl = async ({
  testName,
  category,
  storyName,
  rtl,
}) => {
  const testStoryUrl = createTestStoryUrl({
    testName,
    category,
    storyName,
    rtl,
  });
  await browser.get(testStoryUrl);
};

export const setupBeforeEach = (testName, settings, createTestkit) =>
  beforeEach(() => setupForTest(testName, settings, createTestkit));

export const setupForTest = async (testName, settings, createTestkit) => {
  await navigateToTestUrl({ testName, ...settings });

  const testkit = createTestkit(settings);
  await waitForVisibilityOf(
    await testkit.element(),
    `Cant find ${settings.dataHook}`,
  );
};


text:
$.widget("ui.dialog_tweaks", $.ui.dialog, {

	_state: {

		minimised: false,
		style: ""

	},

	_minimise_btn: null,
	_restore_btn: null,

	_create: function(){
		$.ui.dialog.prototype._create.call(this);

		let close = this.uiDialogTitlebarCloseText.parent();

		this._minimise_btn = $('Minimise');

		this._restore_btn = $('Restore');

		this._restore_btn.on("click", (e) => {
			this.restore(e);

			return false;
		}).insertBefore(close);

		this._minimise_btn.on("click", (e) => {
			this.minimise(e);

			return false;
		}).insertBefore(close);

		if(this.options.id){
			this.uiDialog.attr("id", this.options.id);
		}
	},

	restore: function(event){
		if(!this._state.minimised){
			return;
		}

		if(this.options.before_restore){
			this._trigger("before_restore", event);
		}

		this.uiDialog.removeClass("dialog-tweaks-minimised");
		this.uiDialog.attr("style", this._state.style);

		this.element.show();
		this.uiDialog.draggable("option", "draggable", true);

		this._minimise_btn.css("opacity", 1);
		this._restore_btn.css("opacity", .5);

		this._state.minimised = false;

		if(this.options.after_restore){
			this._trigger("after_restore", event);
		}
	},

	minimise: function(event){
		if(this._state.minimised){
			return;
		}

		if(this.options.before_minimise){
			this._trigger("before_minimise", event);
		}

		this._state.style = this.uiDialog.attr("style");

		this.element.hide();

		this.uiDialog.css("top", "auto");
		this.uiDialog.css("height", "auto");
		this.uiDialog.addClass("dialog-tweaks-minimised");

		this.uiDialog.css({

			position: "fixed",
			left: (this.options.offset_left)? this.options.offset_left : "100px",
			width: (this.options.minimised_width)? this.options.minimised_width : "200px"

		});

		this._minimise_btn.css("opacity", .5);
		this._restore_btn.css("opacity", 1);

		this._state.minimised = true;

		if(this.options.after_minimise){
			this._trigger("after_minimise", event);
		}
	},

	close: function(event){
		$.ui.dialog.prototype.close.call(this, event);

		this.uiDialog.removeClass("dialog-tweaks-minimised");

		this._minimise_btn.css("opacity", 1);
		this._restore_btn.css("opacity", .5);
	},

	open: function(event){
		$.ui.dialog.prototype.open.call(this, event);

		if(this._state.minimised){
			this._state.minimised = false;
			this.minimise();
		}
	}

});


text:
package com.dianping.cat.report.alert.business;

import java.util.Calendar;
import java.util.Date;

import org.unidal.lookup.annotation.Inject;

import com.dianping.cat.alarm.spi.AlertEntity;
import com.dianping.cat.alarm.spi.AlertType;
import com.dianping.cat.alarm.spi.decorator.ProjectDecorator;
import com.dianping.cat.report.alert.summary.AlertSummaryExecutor;

public class BusinessDecorator extends ProjectDecorator {

	public static final String ID = AlertType.Business.getName();

	@Inject
	private AlertSummaryExecutor m_executor;

	@Override
	public String generateContent(AlertEntity alert) {
		Calendar cal = Calendar.getInstance();
		cal.setTime(alert.getDate());
		cal.set(Calendar.SECOND, 0);
		cal.set(Calendar.MILLISECOND, 0);
		Date alertDate = cal.getTime();

		StringBuilder sb = new StringBuilder();
		sb.append(alert.getContent());
		sb.append(buildContactInfo(alert.getDomain()));

		String summaryContext = m_executor.execute(alert.getDomain(), alertDate);
		if (summaryContext != null) {
			sb.append("<br/>").append(summaryContext);
		}

		return sb.toString();
	}

	@Override
	public String generateTitle(AlertEntity alert) {
		StringBuilder sb = new StringBuilder();
		sb.append("[业务告警] [应用名 ").append(alert.getDomain()).append("]");
		sb.append("[业务指标 ").append(alert.getMetric()).append("]");
		return sb.toString();
	}

	@Override
	public String getId() {
		return ID;
	}

}


text:
function [stat] = ft_timelockstatistics(cfg, varargin)

% FT_TIMELOCKSTATISTICS  computes significance probabilities and/or critical values of a parametric statistical test
% or a non-parametric permutation test.
%
% Use as
%   [stat] = ft_timelockstatistics(cfg, timelock1, timelock2, ...)
% where the input data is the result from either FT_TIMELOCKANALYSIS or
% FT_TIMELOCKGRANDAVERAGE.
%
% The configuration can contain the following options for data selection
%   cfg.channel     = Nx1 cell-array with selection of channels (default = 'all'),
%                     see FT_CHANNELSELECTION for details
%   cfg.latency     = [begin end] in seconds or 'all' (default = 'all')
%   cfg.avgoverchan = 'yes' or 'no'                   (default = 'no')
%   cfg.avgovertime = 'yes' or 'no'                   (default = 'no')
%   cfg.parameter   = string                          (default = 'trial' or 'avg')
%
% Furthermore, the configuration should contain
%   cfg.method       = different methods for calculating the significance probability and/or critical value
%                    'montecarlo'    get Monte-Carlo estimates of the significance probabilities and/or critical values from the permutation distribution,
%                    'analytic'      get significance probabilities and/or critical values from the analytic reference distribution (typically, the sampling distribution under the null hypothesis),
%                    'stats'         use a parametric test from the Matlab statistics toolbox,
%                    'crossvalidate' use crossvalidation to compute predictive performance
%
% The other cfg options depend on the method that you select. You
% should read the help of the respective subfunction STATISTICS_XXX
% for the corresponding configuration options and for a detailed
% explanation of each method.
%
% To facilitate data-handling and distributed computing with the peer-to-peer
% module, this function has the following options:
%   cfg.inputfile   =  ...
%   cfg.outputfile  =  ...
% If you specify one of these (or both) the input data will be read from a *.mat
% file on disk and/or the output data will be written to a *.mat file. These mat
% files should contain only a single variable, corresponding with the
% input/output structure.
%
% See also FT_TIMELOCKANALYSIS, FT_TIMELOCKGRANDAVERAGE

% This function depends on STATISTICS_WRAPPER

% Copyright (C) 2005-2006, Robert Oostenveld
%
% This file is part of FieldTrip, see http://www.ru.nl/neuroimaging/fieldtrip
% for the documentation and details.
%
%    FieldTrip is free software: you can redistribute it and/or modify
%    it under the terms of the GNU General Public License as published by
%    the Free Software Foundation, either version 3 of the License, or
%    (at your option) any later version.
%
%    FieldTrip is distributed in the hope that it will be useful,
%    but WITHOUT ANY WARRANTY; without even the implied warranty of
%    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
%    GNU General Public License for more details.
%
%    You should have received a copy of the GNU General Public License
%    along with FieldTrip. If not, see <http://www.gnu.org/licenses/>.
%
% $Id: ft_timelockstatistics.m 3710 2011-06-16 14:04:19Z eelspa $

ft_defaults

% record start time and total processing time
ftFuncTimer = tic();
ftFuncClock = clock();

% set the defaults
if ~isfield(cfg, 'inputfile'),    cfg.inputfile = [];          end
if ~isfield(cfg, 'outputfile'),   cfg.outputfile = [];         end

hasdata = nargin>1;
if ~isempty(cfg.inputfile) % the input data should be read from file
  if hasdata
    error('cfg.inputfile should not be used in conjunction with giving input data to this function');
  else
    for i=1:numel(cfg.inputfile)
      varargin{i} = loadvar(cfg.inputfile{i}, 'data'); % read datasets from array inputfile
    end
  end
end

% % check if the input data is valid for this function
% for i=1:length(varargin)
%   % FIXME at this moment (=10 May) this does not work, because the input might not always have an avg
%   % See freqstatistics
%   %varargin{i} = ft_checkdata(varargin{i}, 'datatype', 'timelock', 'feedback', 'no');
% end

% the low-level data selection function does not know how to deal with other parameters, so work around it
if isfield(cfg, 'parameter')
  if strcmp(cfg.parameter, 'trial') || strcmp(cfg.parameter, 'individual')
    % this is dealt with correctly in the low-level code, even if an average is present
  elseif strcmp(cfg.parameter, 'avg')
    % this is only dealt with in the low-level code if no single-trial/individual data is present
    for i=1:length(varargin)
      if isfield(varargin{i}, 'trial')
        varargin{i} = rmfield(varargin{i}, 'trial');
      end
      if isfield(varargin{i}, 'individual')
        varargin{i} = rmfield(varargin{i}, 'individual');
      end
    end
  else
    % rename the parameter of interest into 'avg'
    fprintf('renaming parameter ''%s'' into ''avg''\n', cfg.parameter);
    for i=1:length(varargin)
      dat         = getsubfield(varargin{i}, cfg.parameter);
      varargin{i} = rmsubfield (varargin{i}, cfg.parameter);
      varargin{i} = setsubfield(varargin{i}, 'avg', dat);
      if isfield(varargin{i}, 'trial')
        varargin{i} = rmfield(varargin{i}, 'trial');
      end
      if isfield(varargin{i}, 'individual')
        varargin{i} = rmfield(varargin{i}, 'individual');
      end
    end
  end
end

% call the general function
[stat, cfg] = statistics_wrapper(cfg, varargin{:});

% add version information to the configuration
cfg.version.name = mfilename('fullpath');
cfg.version.id = '$Id: ft_timelockstatistics.m 3710 2011-06-16 14:04:19Z eelspa $';

% add information about the Matlab version used to the configuration
cfg.callinfo.matlab = version();

% add information about the function call to the configuration
cfg.callinfo.proctime = toc(ftFuncTimer);
cfg.callinfo.calltime = ftFuncClock;
cfg.callinfo.user = getusername();

% remember the configuration of the input data
cfg.previous = [];
for i=1:length(varargin)
  if isfield(varargin{i}, 'cfg')
    cfg.previous{i} = varargin{i}.cfg;
  else
    cfg.previous{i} = [];
  end
end

% remember the exact configuration details
stat.cfg = cfg;

% the output data should be saved to a MATLAB file
if ~isempty(cfg.outputfile)
  savevar(cfg.outputfile, 'stat', stat); % use the variable name "data" in the output file
end


text: from .translator import Translator, SOURCE_LANGS


text:
/**
 * History tab functionality
 */
(function(i) {

	i.About = {

		/**
		 * Checks if there is a new update and shows the about tab if there is
		 */
		checkUpdate: function() {

			// check for update
			Invigilator.common.Settings.getLocal('newUpdate', function(newUpdate) {

				// there is a new update
				if (newUpdate) {

					// show the about tab
					$('.nav a:last').tab('show');

					// reset the newUpdate setting
					i.common.Settings.setLocal('newUpdate', false, function() {

						// clear the 'NEW' badge text
						chrome.browserAction.setBadgeText({
							text: ''
						});

					});
				}
			});

		}

	};

})(Invigilator);


text:
/*
 	Gaussian.h - An Gaussian object

	This class was made to make it easy to understand and use
	Gaussians in real life applications.

	For instructions, go to https://github.com/ivanseidel/Gaussian

	Created by Ivan Seidel Gomes, July, 2013.
	Released into the public domain.
*/

#ifndef Gaussian_h
#define Gaussian_h

#include "math.h"
#include "Arduino.h"

#define MAX_VARIANCE 2147483600

class Gaussian
{
protected:
	/*
		Return the result of the sum of a gaussian
		with _mean and _variance and This gaussian,
		in a NEW object;
	*/
	virtual Gaussian sum(double _mean, double _variance){
		double nMean = (variance * _mean + _variance * mean) / (_variance + variance);
		double nVariance = 1.0 / (1.0/variance + 1.0/_variance);

		return Gaussian(nMean, nVariance);
	}

	/*
		Return the result of the sum of _gaus and This
		gaussian, in a NEW object;
	*/
	virtual Gaussian sum(Gaussian _gaus){
		return sum(_gaus.mean, _gaus.variance);
	}

public:
	/*
		Leave it public, to make it easier
	*/
	double mean, variance;

	/*
		Constructor method
		Default variance is MAC_VARIANCE
	*/
	Gaussian(double _mean = 0.0, double _variance = MAX_VARIANCE){
		mean = _mean;
		variance = _variance;
	}

	/*
		Set the mean to _val
	*/
	virtual Gaussian setMean(double _val){
		mean = _val;

		return *this;
	}

	/*
		Move the mean by _val
	*/
	virtual Gaussian move(double _val){
		mean += _val;

		return *this;
	}

	/*
		Increase the variance by _val
	*/
	virtual Gaussian vary(double _val){
		variance += _val;

		return *this;
	}

	/*
		Increase the variance by _val
	*/
	virtual Gaussian setVariance(double _val){
		variance = _val;

		return *this;
	}

	/*
		Copies the same mean and variance to the current object
	*/
	virtual void operator=(Gaussian _gaus){
		mean = _gaus.mean;
		variance = _gaus.variance;
	}

	/*
		Overrides the + operator to be able to sum with gaussians like:
			Gaussian b = Gaussian(10, 20);
			Gaussian a = b + Gaussian(1,10);
	*/
	virtual Gaussian operator+(Gaussian _gaus){
		return sum(_gaus);
	}

	/*
		Overrides the += operator to be able to sum with gaussians like:
			Gaussian b = Gaussian(10, 20);
			Gaussian a += b;
	*/
	virtual void operator+=(Gaussian _gaus){
		*this = sum(_gaus);
	}

	/*
		Randomize a variable with Gaussian distribuition,
		using it's mean and variance
	*/
	virtual double random(){
		double R1, R2;
		R1 = ::random(MAX_VARIANCE)/(double)MAX_VARIANCE;
		R2 = ::random(MAX_VARIANCE)/(double)MAX_VARIANCE;
		return mean + variance * cos( 2 * M_PI * R1) * sqrt(-log(R2));
	}

	virtual double plot(double x){
		static const float inv_sqrt_2pi = 0.3989422804014327;
		double sigma = sqrt(variance);
	    double a = (x - mean) / sigma;

	    return inv_sqrt_2pi / sigma * exp(-0.5f * a * a);
	}

};

#endif


text:
package org.apache.flink.streaming.connectors.kafka;

import static org.apache.flink.table.descriptors.KafkaValidator.CONNECTOR_VERSION_VALUE_08;

/**
 * Tests for legacy Kafka08JsonTableSourceFactory.
 *
 * @deprecated Ensures backwards compatibility with Flink 1.5. Can be removed once we
 *             drop support for format-specific table sources.
 */
@Deprecated
public class Kafka08JsonTableSourceFactoryTest extends KafkaJsonTableSourceFactoryTestBase {

	@Override
	protected String version() {
		return CONNECTOR_VERSION_VALUE_08;
	}

	@Override
	protected KafkaJsonTableSource.Builder builder() {
		return Kafka08JsonTableSource.builder();
	}
}


text:
const fs = require('fs');
const { print, getAddress } = require('./utils');
const utils = require('web3').utils;
const MAIN_SRC = './dist/tokens';
const IMG_SRC = './src/icons';
const ICON_LINK =
  'https://raw.githubusercontent.com/MyEtherWallet/ethereum-lists/master/src/icons/';
const CONTRACT_LINK =
  'https://raw.githubusercontent.com/MyEtherWallet/ethereum-lists/master/src/tokens/';

function generateMasterFile() {
  const mainArr = [];
  const folderNames = fs.readdirSync(MAIN_SRC);
  const images = fs.readdirSync(IMG_SRC);
  const imageCache = { png: {}, svg: {} };
  images.forEach(img => {
    let addr = getAddress(img);

    if (img.includes('.png') && !imageCache.png[addr])
      imageCache.png[addr] = `${ICON_LINK}${img}`;
    else if (img.includes('.svg') && !imageCache.svg[addr])
      imageCache.svg[addr] = `${ICON_LINK}${img}`;
    else if (!img.includes('.png') && !img.includes('.svg'))
      console.log('\nBad File Type:\n%s', img);
  });
  folderNames.forEach(folderName => {
    const distFiles = fs.readdirSync(`${MAIN_SRC}/${folderName}`);
    const readFile = JSON.parse(
      fs.readFileSync(`${MAIN_SRC}/${folderName}/${distFiles[0]}`, 'utf8')
    );
    const trimmedOffBurner = readFile.filter(item => {
      return item.address !== '0x0000000000000000000000000000000000000000';
    });

    if (trimmedOffBurner.length > 0) {
      trimmedOffBurner.forEach(item => {
        const address = utils.toChecksumAddress(item.address);
        const matchedImagePng = imageCache.png[address];
        const matchedImage = imageCache.svg[address];
        mainArr.push({
          network: folderName,
          symbol: item.symbol,
          name: item.name,
          decimals: item.decimals,
          contract_address: address,
          icon: !!matchedImage
            ? matchedImage
            : !!matchedImagePng
            ? matchedImagePng
            : '',
          icon_png: !!matchedImagePng ? matchedImagePng : '',
          link: `${CONTRACT_LINK}${folderName}/${address}.json`,
          website: item.website
        });
      });
    }
  });

  fs.writeFileSync('./dist/master-file.json', print(mainArr));
}

module.exports = generateMasterFile;


text:
import os
import tvm
from tvm import te
import numpy as np
from tvm import rpc
from tvm.contrib import utils, tflite_runtime

# import tflite_runtime.interpreter as tflite

# NOTE: This script was tested on tensorflow/tflite (v2.4.1)

def skipped_test_tflite_runtime():
    def get_tflite_model_path(target_edgetpu):
        # Return a path to the model
        edgetpu_path = os.getenv("EDGETPU_PATH", "/home/mendel/edgetpu")
        # Obtain mobilenet model from the edgetpu repo path
        if target_edgetpu:
            model_path = os.path.join(
                edgetpu_path, "test_data/mobilenet_v1_1.0_224_quant_edgetpu.tflite"
            )
        else:
            model_path = os.path.join(edgetpu_path, "test_data/mobilenet_v1_1.0_224_quant.tflite")
        return model_path

    def init_interpreter(model_path, target_edgetpu):
        # Initialize interpreter
        if target_edgetpu:
            edgetpu_path = os.getenv("EDGETPU_PATH", "/home/mendel/edgetpu")
            libedgetpu = os.path.join(edgetpu_path, "libedgetpu/direct/aarch64/libedgetpu.so.1")
            interpreter = tflite.Interpreter(
                model_path=model_path, experimental_delegates=[tflite.load_delegate(libedgetpu)]
            )
        else:
            interpreter = tflite.Interpreter(model_path=model_path)
        return interpreter

    def check_remote(server, target_edgetpu=False):
        tflite_model_path = get_tflite_model_path(target_edgetpu)

        # inference via tflite interpreter python apis
        interpreter = init_interpreter(tflite_model_path, target_edgetpu)
        interpreter.allocate_tensors()
        input_details = interpreter.get_input_details()
        output_details = interpreter.get_output_details()

        input_shape = input_details[0]["shape"]
        tflite_input = np.array(np.random.random_sample(input_shape), dtype=np.uint8)
        interpreter.set_tensor(input_details[0]["index"], tflite_input)
        interpreter.invoke()
        tflite_output = interpreter.get_tensor(output_details[0]["index"])

        # inference via remote tvm tflite runtime
        remote = rpc.connect(server.host, server.port)
        dev = remote.cpu(0)
        if target_edgetpu:
            runtime_target = "edge_tpu"
        else:
            runtime_target = "cpu"

        with open(tflite_model_path, "rb") as model_fin:
            runtime = tflite_runtime.create(model_fin.read(), dev, runtime_target)
            runtime.set_input(0, tvm.nd.array(tflite_input, dev))
            runtime.invoke()
            out = runtime.get_output(0)
            np.testing.assert_equal(out.numpy(), tflite_output)

    # Target CPU on coral board
    check_remote(rpc.Server("127.0.0.1"))
    # Target EdgeTPU on coral board
    check_remote(rpc.Server("127.0.0.1"), target_edgetpu=True)

if __name__ == "__main__":
    # skipped_test_tflite_runtime()
    pass


text:
var HTMLWebpackPlugin = require('html-webpack-plugin');
var HTMLWebpackPluginConfig = new HTMLWebpackPlugin({
	template: __dirname + '/app/index.html', // current HTML file
	filename: 'index.html', // name of the newly created HTML file
	inject: 'body'
});

module.exports = {
	entry: __dirname + '/app/index.js', //where it will go
	module: {
		loaders: [
		{
			test: /\.js$/,
			exclude: /node_modules/,
			loader: 'babel-loader'
		}
		]
	},
	output: {
		filename: 'transformed.js',
		path: __dirname //where it will go
	},
	plugins: [HTMLWebpackPluginConfig]
};


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

    <title>About Py4J — Py4J</title>
    <link rel="stylesheet" href="_static/py4jdoc.css" type="text/css" />
    <link rel="stylesheet" href="_static/pygments.css" type="text/css" />

    <link rel="author" title="About these documents" href="#" />
    <link rel="top" title="Py4J" href="index.html" />

Py4J - A Bridge between Python and Java

Navigation

          index

          modules |

Home |

Download |

Doc |

Blog |

github |

About »

On This Page

About Py4J

License

Alternatives to Py4J

This Page

Show Source

Quick search

              <form class="search" action="search.html" method="get">
                <input type="text" name="q" size="18" />
                <input type="submit" value="Go" />
                <input type="hidden" name="check_keywords" value="yes" />
                <input type="hidden" name="area" value="default" />
              </form>

              Enter search terms or a module, class or function name.

About Py4J¶

Py4J is developed by Barthélémy Dagenais. The
goal is to enable developers to program in Python and benefit from Python
libraries such as lxml while being able to
reuse Java libraries and frameworks such as Eclipse. You can see Py4J as an hybrid between a glorified
Remote Procedure Call and using the Java Virtual Machine to run a Python
program.

License¶

Py4J is distributed under the BSD license.

Alternatives to Py4J¶

As opposed to Jython, Py4J does not execute the
Python code in the JVM so it does not need to reimplement the Python language
and developers can use any libraries supported by their Python interpreter such
as libraries written in Cython. Py4J is more focused than JPype. For example, it does not attempt
to link Python threads to Java threads. JPype also uses JNI to communicate with
the JVM while Py4J uses plain old sockets, which are more portable in practice.

In terms of performance, Py4J has a bigger overhead than both of the previous
solutions because it relies on sockets, but if performance is critical to your
application, accessing Java objects from Python programs might not be the best
idea :-) If you have a particular use case that you want to speed up with Py4J,
do not hesitate to write on the mailing list or open an issue and we’ll see
what we can do.

Navigation

          index

          modules |

Home |

Download |

Doc |

Blog |

github |

About »

      © Copyright 2009-2013, Barthélémy Dagenais.
      Created using Sphinx 1.3.1.


text:
module.exports = function () {
  if (Sigma.observers !== undefined) {
    Sigma.observers.forEach(function (observer) {
      observer.disconnect();
    });
  }
  //  Remove eventListeners too for memory leaks!
  var data = document.querySelectorAll('[data-sigma]');
  for (var i = 0; i < data.length; ++i) {
    data[i].removeEventListener('focus', Sigma.contentEditing.editMode, true);
    data[i].removeEventListener('blur', Sigma.contentEditing.viewMode, true);
  }
};


text:
class ChangeVersionsAuthorToText < ActiveRecord::Migration
  def self.up
    change_column :versions, :authors, :text
  end

  def self.down
    change_column :versions, :authors, :string
  end
end