text:
"""
Inspired by the PITF model, we change the loss function into loglikelihood with softmax in multiclassCF context,
which is then equivalent to Neural Network with 1 layer (linear model)
"""

import numpy as np
import cPickle
from MultiClassCF import MCCF
from MultiClassCF import ppl

class NN1Layer(MCCF):
    def __init__(self):
        MCCF.__init__(self)
        # instantiate hyperparameters #
        self.k = 0

        # paras predefined #
        self.r_u = None
        self.r_v = None

        # paras ascome #
        self.u = {}
        self.v = {}

        # paras ascome default #
        self.u_avg = None
        self.v_avg = None

        self.lamda = 0.0

        # results storage #
        self.logfilename = "logs/NN1Layer_GD"
        self.modelconfigurefile = "modelconfigures/NN1Layer_GD_config"

        ### test ###
        self.delt_r_u = None
        self.delt_r_v = None
        self.delt_u = {}
        self.delt_v = {}

    def fit(self, training, valid, model_hyperparameters, max_epoch=1000, SGDstep=0.001, SCALE=0.1):
        # model independent #
        self.set_model_hyperparameters(model_hyperparameters)
        self.L = training.L()
        self.SGDstep = SGDstep
        self.SCALE = SCALE

        with open(self.logfilename, "a") as logf:
            logf.write("model_hyperparameters: " + str(model_hyperparameters) + "\n")
            logf.write("SGDstep: " + str(self.SGDstep) + "\n")
            logf.write("SCALE: " + str(self.SCALE) + "\n")

        self.modelconfigurefile += str(model_hyperparameters) + "_SGDstep" + str(self.SGDstep) + "_SCALE" + str(
            self.SCALE)

        self.basicInitialize()

        ### test ###
        self.modelconfigLoad("modelconfigures/NN1Layer_config_PITFsynthetic_N500_M500_L3_K15_0.7train[15]_SGDstep0.01_SCALE0.1")
        for key in self.u.keys():
            self.delt_u[key] = np.zeros(self.u[key].shape, dtype=np.float64)
        for key in self.v.keys():
            self.delt_v[key] = np.zeros(self.v[key].shape, dtype=np.float64)

        # SGD #
        loss_valid = None
        loss_valid_minimum = None
        for epoch in xrange(max_epoch):
            loss_train_old = self.loss(training)
            loss_valid_old = self.loss(valid)
            Nsamp = 0
            for samp in training.sample():
                self.initialize(samp[0], samp[1])
                self.stepupdate(samp)
                Nsamp += 1
            self.update(Nsamp)
            self.averageEmbedding()
            loss_train_new = self.loss(training)
            loss_valid_new = self.loss(valid)
            print "before epoch, train", loss_train_old
            print "after epoch, train", loss_train_new
            print "before epoch, valid", loss_valid_old
            print "after epoch, valid", loss_valid_new
            with open(self.logfilename, "a") as logf:
                logf.write("after epoch %d loss training: %f\n" % (epoch, loss_train_new))
                logf.write("after epoch %d loss valid: %f\n" % (epoch, loss_valid_new))
            if loss_valid is not None and loss_valid_new >= loss_valid:
                with open(self.logfilename, "a") as logf:
                    logf.write("overfitting in epoch: %d\n" % epoch)
            else:
                if loss_valid_minimum is None or loss_valid_new < loss_valid_minimum:
                    loss_valid_minimum = loss_valid_new
                    self.modelconfigStore()
            loss_valid = loss_valid_new
        self.modelconfigStore(self.modelconfigurefile + "end_epoch" + str(max_epoch))
        return self

    def set_model_hyperparameters(self, model_hyperparameters):
        if len(model_hyperparameters) != 1:
            raise ValueError("number of hyperparameters wrong")
        self.k = model_hyperparameters[0]

    def basicInitialize(self):
        self.r_u = np.random.normal(0.0, self.SCALE, size=(self.L, self.k))
        self.r_v = np.random.normal(0.0, self.SCALE, size=(self.L, self.k))
        self.delt_r_u = np.zeros(self.r_u.shape, dtype=np.float64)
        self.delt_r_v = np.zeros(self.r_v.shape, dtype=np.float64)
        self.u_avg = np.zeros(self.k)
        self.v_avg = np.zeros(self.k)

    def initialize(self, uid, iid, predict=False):
        ## according to [1] in MultiMF ##
        if uid not in self.u:
            if predict:
                self.u[uid] = self.u_avg
            else:
                self.u[uid] = np.random.normal(0.0, self.SCALE, size=self.k)
            self.delt_u[uid] = np.zeros(self.u[uid].shape, dtype=np.float64)
        if iid not in self.v:
            if predict:
                self.v[iid] = self.v_avg
            else:
                self.v[iid] = np.random.normal(0.0, self.SCALE, size=self.k)
            self.delt_v[iid] = np.zeros(self.v[iid].shape, dtype=np.float64)
        return self

    # def update(self, instance):
    #     loss_before = self.singleLoss(instance)
    #     uid, iid, lid = instance
    #     m = np.tensordot(self.r_u, self.u[uid], axes=(1, 0)) + np.tensordot(self.r_v, self.v[iid], axes=(1, 0))
    #     expm = np.exp(m)
    #     expmsum = np.sum(expm)
    #     mgrad = expm / expmsum
    #     mgrad[lid] = mgrad[lid] - 1.0
    #     mgrad = - mgrad
    #     # gradient for embeddings #
    #     delt_u = np.tensordot(mgrad, self.r_u, axes = (0,0))
    #     delt_r_u = np.outer(mgrad, self.u[uid])
    #     delt_v = np.tensordot(mgrad, self.r_v, axes = (0,0))
    #     delt_r_v = np.outer(mgrad, self.v[iid])
    #     # update #
    #     self.u[uid] += (self.SGDstep * delt_u)
    #     self.v[iid] += (self.SGDstep * delt_v)
    #     self.r_u += (self.SGDstep * delt_r_u)
    #     self.r_v += (self.SGDstep * delt_r_v)
    #     loss_after = self.singleLoss(instance)
    #     if loss_after > loss_before:
    #         print "single loss increase", loss_before, loss_after
    #     return self

    def stepupdate(self, instance):
        uid, iid, lid = instance
        m = np.tensordot(self.r_u, self.u[uid], axes=(1, 0)) + np.tensordot(self.r_v, self.v[iid], axes=(1, 0))
        expm = np.exp(m)
        expmsum = np.sum(expm)
        mgrad = expm / expmsum
        mgrad[lid] = mgrad[lid] - 1.0
        mgrad = - mgrad
        # gradient for embeddings #
        delt_u = np.tensordot(mgrad, self.r_u, axes = (0,0))
        delt_r_u = np.outer(mgrad, self.u[uid])
        delt_v = np.tensordot(mgrad, self.r_v, axes = (0,0))
        delt_r_v = np.outer(mgrad, self.v[iid])
        # update #
        self.delt_u[uid] += delt_u
        self.delt_v[iid] += delt_v
        self.delt_r_u += delt_r_u
        self.delt_r_v += delt_r_v
        return self

    def update(self, Nsamp):
        for uid in self.delt_u.keys():
            self.u[uid] += (self.SGDstep * self.delt_u[uid]/Nsamp)
            del self.delt_u[uid]
            self.delt_u[uid] = np.zeros(self.u[uid].shape, dtype=np.float64)
        for iid in self.delt_v.keys():
            self.v[iid] += (self.SGDstep * self.delt_v[iid]/Nsamp)
            del self.delt_v[iid]
            self.delt_v[iid] = np.zeros(self.v[iid].shape, dtype=np.float64)
        self.r_u += (self.SGDstep * self.delt_r_u/Nsamp)
        del self.delt_r_u
        self.delt_r_u = np.zeros(self.r_u.shape, dtype=np.float64)
        self.r_v += (self.SGDstep * self.delt_r_v/Nsamp)
        del self.delt_r_v
        self.delt_r_v = np.zeros(self.r_v.shape, dtype=np.float64)

    def averageEmbedding(self):
        self.u_avg = np.mean(np.array([u for u in self.u.values()]), axis=0)
        self.v_avg = np.mean(np.array([v for v in self.v.values()]), axis=0)

    def predict(self, uid, iid, distribution = True):
        self.initialize(uid, iid, predict = True)
        m = np.tensordot(self.r_u, self.u[uid], axes=(1, 0)) + np.tensordot(self.r_v, self.v[iid], axes=(1, 0))
        expm = np.exp(m)
        expmsum = np.sum(expm)
        if distribution:
            return expm / expmsum
        else:
            return np.argmax(expm)

    ### test ###
    def singleLoss(self, instance):
        predprod = self.predict(instance[0], instance[1], distribution=True)
        loss = ppl(predprob=predprod, truelabel=instance[2])
        return loss

    def modelconfigStore(self, modelconfigurefile=None):
        if modelconfigurefile is None:
            modelconfigurefile = self.modelconfigurefile
        paras = {"u": self.u, "v": self.v, "r_u": self.r_u, "r_v": self.r_v, "u_avg": self.u_avg, "v_avg": self.v_avg}
        with open(modelconfigurefile, "w") as f:
            cPickle.dump(paras, f)

    def modelconfigLoad(self, modelconfigurefile=None):
        if modelconfigurefile is None:
            modelconfigurefile = self.modelconfigurefile
        with open(modelconfigurefile, "r") as f:
            paras = cPickle.load(f)
        # write to model parameters #
        self.u = paras["u"]
        self.v = paras["v"]
        self.r_u = paras["r_u"]
        self.r_v = paras["r_v"]
        self.u_avg = paras["u_avg"]
        self.v_avg = paras["v_avg"]
        self.L = self.r_u.shape[0]
        print "model successfully loaded from " + modelconfigurefile


text:
<?php

namespace l3l0\Bundle\OpenSocialBundle\Factory\Auth;

class NetlogProviderAuthFactory extends \l3l0\Bundle\OpenSocialBundle\Factory\Auth\OAuth3AuthFactory
{
}

redpajama_set_name: RedPajamaGithub


text:
package org.asnelt.derandom;

import android.content.SharedPreferences;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.preference.EditTextPreference;
import androidx.preference.ListPreference;
import androidx.preference.Preference;
import androidx.preference.PreferenceFragmentCompat;

import android.text.InputType;
import android.view.MenuItem;
import android.widget.EditText;
import android.widget.Toast;

/**
 * A PreferenceActivity that presents a set of application settings.
 */
public class SettingsActivity extends AppCompatActivity
        implements SharedPreferences.OnSharedPreferenceChangeListener {
    /** Key to identify the auto-detect preference. */
    public static final String KEY_PREF_AUTO_DETECT = "pref_auto_detect";
    /** Key to identify the predictions length preference. */
    public static final String KEY_PREF_PREDICTION_LENGTH = "pref_prediction_length";
    /** Key to identify the colored past preference. */
    public static final String KEY_PREF_COLORED_PAST = "pref_colored_past";
    /** Key to identify the history length preference. */
    public static final String KEY_PREF_HISTORY_LENGTH = "pref_history_length";
    /** Key to identify the parameter base preference. */
    public static final String KEY_PREF_PARAMETER_BASE = "pref_parameter_base";
    /** Key to identify the socket port preference. */
    public static final String KEY_PREF_SOCKET_PORT = "pref_socket_port";

    /** Reference to a SettingsFragment. */
    private SettingsFragment mFragment;

    /**
     * Initializes the activity.
     * @param savedInstanceState Bundle to recover the state
     */
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_settings);
        mFragment = new SettingsFragment();
        getSupportFragmentManager()
                .beginTransaction()
                .replace(R.id.preferences_layout, mFragment)
                .commit();
    }

    /**
     * Registers a listener for preference changes.
     */
    @Override
    protected void onResume() {
        super.onResume();
        SharedPreferences preferences;
        preferences = getFragmentSharedPreferences();
        preferences.registerOnSharedPreferenceChangeListener(this);
        // Initialize summaries
        onSharedPreferenceChanged(preferences, KEY_PREF_PREDICTION_LENGTH);
        onSharedPreferenceChanged(preferences, KEY_PREF_HISTORY_LENGTH);
        onSharedPreferenceChanged(preferences, KEY_PREF_PARAMETER_BASE);
        onSharedPreferenceChanged(preferences, KEY_PREF_SOCKET_PORT);
    }

    /**
     * Unregisters a listener for preference changes.
     */
    @Override
    protected void onPause() {
        super.onPause();
        SharedPreferences preferences;
        preferences = getFragmentSharedPreferences();
        preferences.unregisterOnSharedPreferenceChangeListener(this);
    }

    /**
     * Updates the preference summaries.
     * @param preferences shared preferences
     * @param key the key of the preference that changed
     */
    @Override
    public void onSharedPreferenceChanged(SharedPreferences preferences, String key) {
        Preference preference;
        preference = findFragmentPreference(key);
        switch (key) {
            case KEY_PREF_PREDICTION_LENGTH:
            case KEY_PREF_HISTORY_LENGTH:
            case KEY_PREF_SOCKET_PORT:
                EditTextPreference numberPreference = (EditTextPreference) preference;
                String numberString = numberPreference.getText();
                try {
                    int numberInteger = Integer.parseInt(numberString);
                    // Check that numbers fit into a single string
                    if (numberInteger > Integer.MAX_VALUE
                            / (Long.toString(Long.MAX_VALUE).length()+1)) {
                        throw new NumberFormatException();
                    }
                    if (key.equals(SettingsActivity.KEY_PREF_SOCKET_PORT)
                            && numberInteger > 0xFFFF) {
                        throw new NumberFormatException();
                    }
                } catch (NumberFormatException e) {
                    // Correct to default value
                    String defaultValue = "";
                    switch (key) {
                        case SettingsActivity.KEY_PREF_PREDICTION_LENGTH:
                            defaultValue = getResources().getString(
                                    R.string.pref_prediction_length_default_value);
                            break;
                        case SettingsActivity.KEY_PREF_HISTORY_LENGTH:
                            defaultValue = getResources().getString(
                                    R.string.pref_history_length_default_value);
                            break;
                        case SettingsActivity.KEY_PREF_SOCKET_PORT:
                            defaultValue = getResources().getString(
                                    R.string.pref_socket_port_default_value);
                            break;
                    }
                    numberPreference.setText(defaultValue);
                    String errorMessage = getResources().getString(R.string.number_error_message);
                    Toast.makeText(getApplicationContext(), errorMessage,
                            Toast.LENGTH_SHORT).show();
                }
                String summary = numberPreference.getText();
                if (key.equals(SettingsActivity.KEY_PREF_SOCKET_PORT)) {
                    summary = getResources().getString(R.string.pref_socket_port_summary) + " "
                            + summary;
                } else if (summary != null && summary.equals("1")) {
                    if (key.equals(SettingsActivity.KEY_PREF_HISTORY_LENGTH)) {
                        summary += " " + getResources().getString(
                                R.string.pref_history_length_summary_singular);
                    } else {
                        summary += " " + getResources().getString(
                                R.string.pref_prediction_length_summary_singular);
                    }
                } else {
                    if (key.equals(SettingsActivity.KEY_PREF_HISTORY_LENGTH)) {
                        summary += " " + getResources().getString(
                                R.string.pref_history_length_summary_plural);
                    } else {
                        summary += " " + getResources().getString(
                                R.string.pref_prediction_length_summary_plural);
                    }
                }
                numberPreference.setSummary(summary);
                break;
            case KEY_PREF_PARAMETER_BASE:
                ListPreference parameterBasePreference = (ListPreference) preference;
                parameterBasePreference.setSummary(parameterBasePreference.getEntry());
                break;
        }
    }

    /**
     * Callback method for item selected.
     * @param item the selected item
     * @return false to allow normal menu processing to proceed, true to consume it here
     */
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            this.finish();
            return true;
        } else {
            return super.onOptionsItemSelected(item);
        }
    }

    /**
     * Returns the shared preferences by means of a preference fragment.
     * @return the shared preferences
     */
    private SharedPreferences getFragmentSharedPreferences() {
        return mFragment.getPreferenceScreen().getSharedPreferences();
    }

    /**
     * Finds a preference by means of a preference fragment.
     * @param key the key of the preference
     * @return the preference
     */
    private Preference findFragmentPreference(String key) {
        return mFragment.findPreference(key);
    }

    /**
     * This class implements a preference fragment that adds all preferences from a common resource.
     */
    public static class SettingsFragment extends PreferenceFragmentCompat {
        /**
         * Initializes the fragment by adding all preference items from a resource.
         * @param savedInstanceState Bundle to restore a state
         * @param rootKey the key to root this fragment with
         */
        @Override
        public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {
            setPreferencesFromResource(R.xml.preferences, rootKey);

            EditTextPreference editTextPreference;

            editTextPreference = getPreferenceManager().findPreference("pref_prediction_length");
            if (editTextPreference != null) {
                editTextPreference.setOnBindEditTextListener(
                        new EditTextPreference.OnBindEditTextListener() {
                            @Override
                            public void onBindEditText(@NonNull EditText editText) {
                                editText.setInputType(InputType.TYPE_CLASS_NUMBER);
                            }
                        });
            }

            editTextPreference = getPreferenceManager().findPreference("pref_history_length");
            if (editTextPreference != null) {
                editTextPreference.setOnBindEditTextListener(
                        new EditTextPreference.OnBindEditTextListener() {
                            @Override
                            public void onBindEditText(@NonNull EditText editText) {
                                editText.setInputType(InputType.TYPE_CLASS_NUMBER);
                            }
                        });
            }

            editTextPreference = getPreferenceManager().findPreference("pref_socket_port");
            if (editTextPreference != null) {
                editTextPreference.setOnBindEditTextListener(
                        new EditTextPreference.OnBindEditTextListener() {
                            @Override
                            public void onBindEditText(@NonNull EditText editText) {
                                editText.setInputType(InputType.TYPE_CLASS_NUMBER);
                            }
                        });
            }
        }
    }
}


text:
package jo.sm.plugins.ship.text;

import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;

import jo.sm.data.BlockTypes;
import jo.sm.data.SparseMatrix;
import jo.sm.data.StarMade;
import jo.sm.logic.PluginUtils;
import jo.sm.mods.IBlocksPlugin;
import jo.sm.mods.IPluginCallback;
import jo.sm.plugins.ship.imp.PlotLogic;
import jo.sm.ship.data.Block;
import jo.sm.ship.logic.ShipLogic;
import jo.vecmath.Point3i;

public class ImagePlugin implements IBlocksPlugin
{
    public static final String NAME = "Image";
    public static final String DESC = "Paint image on the hull.";
    public static final String AUTH = "Jo Jaquinta";
    public static final int[][] CLASSIFICATIONS =
        {
        { TYPE_SHIP, SUBTYPE_PAINT },
        { TYPE_STATION, SUBTYPE_PAINT },
        { TYPE_SHOP, SUBTYPE_PAINT },
        };

    private Point3i mStartingPoint;
    private Point3i mAdvanceVector;
    private int mAdvanceLength;
    private Point3i mHeightVector;
    private int mHeightLength;
    private Point3i mDepthVector;
    private int mDepthLength;

    @Override
    public String getName()
    {
        return NAME;
    }

    @Override
    public String getDescription()
    {
        return DESC;
    }

    @Override
    public String getAuthor()
    {
        return AUTH;
    }

    @Override
    public Object newParameterBean()
    {
        return new ImageParameters();
    }
	@Override
	public void initParameterBean(SparseMatrix<Block> original, Object params,
			StarMade sm, IPluginCallback cb)
	{
	}

    @Override
    public int[][] getClassifications()
    {
        return CLASSIFICATIONS;
    }

    @Override
    public SparseMatrix<Block> modify(SparseMatrix<Block> original,
            Object p, StarMade sm, IPluginCallback cb)
    {
        ImageParameters params = (ImageParameters)p;
        Point3i lower = new Point3i();
        Point3i upper = new Point3i();
        PluginUtils.getEffectiveSelection(sm, original, lower, upper);
        if (cb != null) cb.setStatus("Adding text");
        setupExtent(lower, upper);
        BufferedImage text = setupImage(params, cb);
        if (text == null)
            return null;

        if (cb != null) cb.startTask(mAdvanceLength);
        SparseMatrix<Block> modified = new SparseMatrix<Block>(original);
        Point3i advance = new Point3i(mStartingPoint);
        for (int x = 0; x < mAdvanceLength; x++)
        {
            Point3i height = new Point3i(advance);
            for (int y = 0; y < mHeightLength; y++)
            {
                int rgb = text.getRGB(x, y);
                if ((rgb&0xFF000000) != 0)
                {
                    System.out.print("X");
                    short id = PlotLogic.mapColor(rgb);
                    Point3i depth = new Point3i(height);
                    for (int z = 0; z < mDepthLength; z++)
                    {
                        Block oldBlock = modified.get(depth);
                        if (oldBlock != null)
                        {
                            Block newBlock = BlockTypes.colorize(oldBlock, id);
                            modified.set(depth, newBlock);
                        }
                        depth.add(mDepthVector);
                    }
                }
                else
                    System.out.print(" ");
                height.add(mHeightVector);
            }
            System.out.println();
            advance.add(mAdvanceVector);
            if (cb != null) cb.workTask(1);
        }
        ShipLogic.ensureCore(modified);
        if (cb != null) cb.endTask();
        return modified;
    }

    private BufferedImage setupImage(ImageParameters params, IPluginCallback cb)
    {
        BufferedImage picture = null;
        try
        {
            picture = ImageIO.read(new File(params.getFile()));
            BufferedImage img = new BufferedImage(mAdvanceLength, mHeightLength, BufferedImage.TYPE_4BYTE_ABGR);
            Graphics g = img.getGraphics();
            g.drawImage(picture, 0, 0, mAdvanceLength, mHeightLength, 0, 0, picture.getWidth(), picture.getHeight(), null);
            g.dispose();
            return img;
        }
        catch (IOException e)
        {
            cb.setError(e);
            return null;
        }
    }

    private void setupExtent(Point3i lower, Point3i upper)
    {
        int xSpan = upper.x - lower.x + 1;
        int ySpan = upper.y - lower.y + 1;
        int zSpan = upper.z - lower.z + 1;
        mStartingPoint = lower;
        mAdvanceLength = Math.max(xSpan, Math.max(ySpan, zSpan));
        if (mAdvanceLength == xSpan)
        {
            mAdvanceVector = new Point3i(1, 0, 0);
            if (ySpan >= zSpan)
            {
                mHeightVector = new Point3i(0, 1, 0);
                mHeightLength = ySpan;
                mDepthVector = new Point3i(0, 0, 1);
                mDepthLength = zSpan;
            }
            else
            {
                mHeightVector = new Point3i(0, 0, 1);
                mHeightLength = zSpan;
                mDepthVector = new Point3i(0, 1, 0);
                mDepthLength = ySpan;
            }
        }
        else if (mAdvanceLength == ySpan)
        {
            mAdvanceVector = new Point3i(0, 1, 0);
            if (xSpan >= zSpan)
            {
                mHeightVector = new Point3i(1, 0, 0);
                mHeightLength = xSpan;
                mDepthVector = new Point3i(0, 0, 1);
                mDepthLength = zSpan;
            }
            else
            {
                mHeightVector = new Point3i(0, 0, 1);
                mHeightLength = zSpan;
                mDepthVector = new Point3i(1, 0, 0);
                mDepthLength = xSpan;
            }
        }
        else if (mAdvanceLength == zSpan)
        {
            mAdvanceVector = new Point3i(0, 0, 1);
            if (xSpan >= ySpan)
            {
                mHeightVector = new Point3i(1, 0, 0);
                mHeightLength = xSpan;
                mDepthVector = new Point3i(0, 1, 0);
                mDepthLength = ySpan;
            }
            else
            {
                mHeightVector = new Point3i(0, 1, 0);
                mHeightLength = ySpan;
                mDepthVector = new Point3i(1, 0, 0);
                mDepthLength = xSpan;
            }
        }
        System.out.println("Advance="+mAdvanceVector+" x "+mAdvanceLength);
        System.out.println("Height="+mHeightVector+" x "+mHeightLength);
        System.out.println("Depth="+mDepthVector+" x "+mDepthLength);
    }
}


text: Rails.application.config.session_store :cookie_store, key: '_amass_session'


text:
package com.method76.common.base;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.TypedValue;
import android.widget.ProgressBar;
import android.widget.Toast;

import com.method76.comics.marvel.common.constant.AppConst;
import com.method76.common.abst.BaseUiInterface;
import com.method76.common.constant.CommonConst;

import java.util.Calendar;

/**
 * Created by Sungjoon Kim on 2016-01-29.
 */
public class BaseCompatActivity extends AppCompatActivity implements
        CommonConst, AppConst, BaseUiInterface {

    private BaseApplication application;
    private boolean sessionExpired;
    private long lastTimestamp;
    private Toast mCurrentToast;
    private ProgressBar progress;
    protected boolean canEscape;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        application = (BaseApplication)getApplication();
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
    }

    @Override
    protected void onResume() {
        super.onResume();
        checkSessionExpired();
    }

    @Override
    protected void onPause() {
        super.onPause();
        checkSessionExpired();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    public boolean checkSessionExpired(){
        if(lastTimestamp != 0){
            long interval = getThisTIme() - lastTimestamp;
            if(interval > TIMEOUT_SESSION){
                return true;
            }
        }
        return false;
    }

    public String getClassname(){
        return this.getClass().getSimpleName();
    }

    public BaseApplication getCustomApplication(){
        return (BaseApplication)getApplication();
    }

    private long getThisTIme(){
       return  Calendar.getInstance().getTimeInMillis();
    }

    public int dpToPixel(float dp){
        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp,
                getResources().getDisplayMetrics());
    }

    public int pixelToDp(int px) {
        return (int) (px / getResources().getDisplayMetrics().density);
    }

    @Override
    public void showToast(CharSequence text) {
        if (null != mCurrentToast) {
            mCurrentToast.cancel();
        }
        mCurrentToast = Toast.makeText(this, text, Toast.LENGTH_SHORT);
        mCurrentToast.show();
    }
    @Override
    public ProgressBar getBaseProgress() {
        return this.progress;
    }
    @Override
    public void setBaseProgress(ProgressBar progress) {
        this.progress = progress;
    }

    public BaseApplication getBaseApplication(){
        return application;
    }

}


text:
A summary of all of the updates.

## 1.0.0
- Initial release


text:
package org.kie.workbench.common.screens.library.client.screens;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

import org.guvnor.common.services.project.client.context.WorkspaceProjectContext;
import org.guvnor.common.services.project.client.security.ProjectController;
import org.guvnor.structure.client.security.OrganizationalUnitController;
import org.guvnor.structure.events.AfterEditOrganizationalUnitEvent;
import org.guvnor.structure.organizationalunit.OrganizationalUnit;
import org.jboss.errai.common.client.dom.HTMLElement;
import org.jboss.errai.ioc.client.api.ManagedInstance;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.kie.workbench.common.screens.library.api.LibraryService;
import org.kie.workbench.common.screens.library.client.screens.importrepository.ImportRepositoryPopUpPresenter;
import org.kie.workbench.common.screens.library.client.screens.organizationalunit.contributors.edit.EditContributorsPopUpPresenter;
import org.kie.workbench.common.screens.library.client.screens.organizationalunit.contributors.tab.ContributorsListPresenter;
import org.kie.workbench.common.screens.library.client.screens.organizationalunit.delete.DeleteOrganizationalUnitPopUpPresenter;
import org.kie.workbench.common.screens.library.client.util.LibraryPlaces;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import org.uberfire.mocks.CallerMock;

import static org.mockito.Mockito.*;

@RunWith(MockitoJUnitRunner.class)
public class LibraryScreenTest {

    @Mock
    private LibraryScreen.View view;

    @Mock
    private ManagedInstance<EditContributorsPopUpPresenter> editContributorsPopUpPresenters;

    @Mock
    private ManagedInstance<DeleteOrganizationalUnitPopUpPresenter> deleteOrganizationalUnitPopUpPresenters;

    @Mock
    private OrganizationalUnitController organizationalUnitController;

    @Mock
    private ProjectController projectController;

    @Mock
    private EmptyLibraryScreen emptyLibraryScreen;

    @Mock
    private PopulatedLibraryScreen populatedLibraryScreen;

    @Mock
    private OrgUnitsMetricsScreen orgUnitsMetricsScreen;

    @Mock
    private OrgUnitsMetricsScreen.View orgUnitsMetricsView;

    @Mock
    private ContributorsListPresenter contributorsListPresenter;

    @Mock
    private LibraryService libraryService;

    @Mock
    private LibraryPlaces libraryPlaces;

    @Mock
    private EditContributorsPopUpPresenter editContributorsPopUpPresenter;

    @Mock
    private DeleteOrganizationalUnitPopUpPresenter deleteOrganizationalUnitPopUpPresenter;

    @Mock
    private ImportRepositoryPopUpPresenter importRepositoryPopUpPresenter;

    @Mock
    private WorkspaceProjectContext projectContext;

    private LibraryScreen libraryScreen;

    @Before
    public void setup() {
        doReturn(editContributorsPopUpPresenter).when(editContributorsPopUpPresenters).get();
        doReturn(deleteOrganizationalUnitPopUpPresenter).when(deleteOrganizationalUnitPopUpPresenters).get();
        doReturn(orgUnitsMetricsView).when(orgUnitsMetricsScreen).getView();

        doReturn(true).when(projectController).canCreateProjects();
        doReturn(true).when(organizationalUnitController).canUpdateOrgUnit(any());
        doReturn(true).when(organizationalUnitController).canDeleteOrgUnit(any());

        doReturn(mock(PopulatedLibraryScreen.View.class)).when(populatedLibraryScreen).getView();
        doReturn(mock(EmptyLibraryScreen.View.class)).when(emptyLibraryScreen).getView();

        final OrganizationalUnit organizationalUnit = mock(OrganizationalUnit.class);
        doReturn(Optional.of(organizationalUnit)).when(projectContext).getActiveOrganizationalUnit();
        when(projectContext.getActiveWorkspaceProject()).thenReturn(Optional.empty());
        when(projectContext.getActiveModule()).thenReturn(Optional.empty());
        when(projectContext.getActiveRepositoryRoot()).thenReturn(Optional.empty());
        when(projectContext.getActivePackage()).thenReturn(Optional.empty());

        libraryScreen = new LibraryScreen(view,
                                          deleteOrganizationalUnitPopUpPresenters,
                                          editContributorsPopUpPresenters,
                                          projectContext,
                                          organizationalUnitController,
                                          projectController,
                                          emptyLibraryScreen,
                                          populatedLibraryScreen,
                                          orgUnitsMetricsScreen,
                                          contributorsListPresenter,
                                          new CallerMock<>(libraryService),
                                          libraryPlaces);
    }

    @Test
    public void setupTest() {
        final OrganizationalUnit organizationalUnit = mock(OrganizationalUnit.class);
        doReturn("name").when(organizationalUnit).getName();
        doReturn(Optional.of(organizationalUnit)).when(projectContext).getActiveOrganizationalUnit();
        doReturn(12).when(contributorsListPresenter).getContributorsCount();

        libraryScreen.init();

        verify(view).init(libraryScreen);
        verify(view).setTitle("name");
        verify(view).setContributorsCount(12);
    }

    @Test
    public void trySamplesWithPermissionTest() {
        libraryScreen.trySamples();

        verify(libraryPlaces).goToTrySamples();
    }

    @Test
    public void trySamplesWithoutPermissionTest() {
        doReturn(false).when(projectController).canCreateProjects();

        libraryScreen.trySamples();

        verify(libraryPlaces,
               never()).goToTrySamples();
    }

    @Test
    public void importProjectWithPermissionTest() {
        libraryScreen.importProject();

        verify(libraryPlaces).goToImportRepositoryPopUp();
    }

    @Test
    public void importProjectWithoutPermissionTest() {
        doReturn(false).when(projectController).canCreateProjects();

        libraryScreen.importProject();

        verify(libraryPlaces,
               never()).goToImportRepositoryPopUp();
    }

    @Test
    public void editContributorsWithPermissionTest() {
        libraryScreen.editContributors();

        verify(editContributorsPopUpPresenter).show(any());
    }

    @Test
    public void editContributorsWithoutPermissionTest() {
        doReturn(false).when(organizationalUnitController).canUpdateOrgUnit(any());

        libraryScreen.editContributors();

        verify(editContributorsPopUpPresenter,
               never()).show(any());
    }

    @Test
    public void deleteWithPermissionTest() {
        libraryScreen.delete();

        verify(deleteOrganizationalUnitPopUpPresenter).show(any());
    }

    @Test
    public void deleteWithoutPermissionTest() {
        doReturn(false).when(organizationalUnitController).canDeleteOrgUnit(any());

        libraryScreen.delete();

        verify(deleteOrganizationalUnitPopUpPresenter,
               never()).show(any());
    }

    @Test
    public void showProjectsTest() {
        doReturn(true).when(libraryService).hasProjects(any());
        final HTMLElement populatedLibraryScreenElement = mock(HTMLElement.class);
        when(populatedLibraryScreen.getView().getElement()).thenReturn(populatedLibraryScreenElement);
        doReturn(3).when(populatedLibraryScreen).getProjectsCount();

        libraryScreen.showProjects();

        verify(view).updateContent(populatedLibraryScreenElement);
        verify(view).setProjectsCount(3);
    }

    @Test
    public void showNoProjectsTest() {
        doReturn(false).when(libraryService).hasProjects(any());
        final HTMLElement emptyLibraryScreenElement = mock(HTMLElement.class);
        when(emptyLibraryScreen.getView().getElement()).thenReturn(emptyLibraryScreenElement);

        libraryScreen.showProjects();

        verify(view).updateContent(emptyLibraryScreenElement);
        verify(view).setProjectsCount(0);
    }

    @Test
    public void organizationalUnitEditedTest() {
        final OrganizationalUnit organizationalUnit = mock(OrganizationalUnit.class);
        final List<String> contributors = new ArrayList<>();
        contributors.add("admin");
        doReturn(contributors).when(organizationalUnit).getContributors();

        libraryScreen.organizationalUnitEdited(new AfterEditOrganizationalUnitEvent(mock(OrganizationalUnit.class),
                                                                                organizationalUnit));

        verify(view).setContributorsCount(contributors.size());
    }

    @Test
    public void showMetrics() {
        libraryScreen.showMetrics();
        verify(orgUnitsMetricsScreen).refresh();
        verify(view).updateContent(any());
    }
}


text:
        <md-button ng-click="ipfc.download()"
                   class="md-text-icon-button md-raised"
                   aria-label="{{ 'ERMS_REPOS.VIEW_META' | translate }}">
            file_download
            {{ 'COMMON.DOWNLOAD' | translate }}
        </md-button>

No preview available


text:
Rails.application.configure do
  config.cache_classes = true
  config.eager_load = true
  config.consider_all_requests_local = false
  config.action_controller.perform_caching = true
  config.log_level = :info
  config.i18n.fallbacks = true
  config.active_support.deprecation = :notify
  config.log_formatter = ::Logger::Formatter.new

  # Access secret base key via AppConfig
  secrets.secret_key_base = AppConfig.secret_key_base
end


text:
#ifndef FIXTUREMANAGER_H
#define FIXTUREMANAGER_H

#include <QQmlListProperty>
#include <QQuickView>
#include <QMultiHash>
#include <QObject>
#include <QList>

#include "scenevalue.h"

class Doc;
class Fixture;

class FixtureManager : public QObject
{
    Q_OBJECT
    Q_PROPERTY(int fixturesCount READ fixturesCount NOTIFY fixturesCountChanged)
    Q_PROPERTY(QQmlListProperty<Fixture> fixtures READ fixtures)

public:
    FixtureManager(QQuickView *view, Doc *doc, QObject *parent = 0);

    Q_INVOKABLE quint32 invalidFixture();
    Q_INVOKABLE quint32 fixtureForAddress(quint32 index);
    Q_INVOKABLE bool addFixture(QString manuf, QString model, QString mode, QString name,
                                int uniIdx, int address, int channels, int quantity, quint32 gap,
                                qreal xPos, qreal yPos);
    Q_INVOKABLE QString channelIcon(quint32 fxID, quint32 chIdx);

    Q_INVOKABLE void setChannelValue(quint32 fixtureID, quint32 channelIndex, quint8 value);
    Q_INVOKABLE void setIntensityValue(quint8 value);
    Q_INVOKABLE void setColorValue(quint8 red, quint8 green, quint8 blue,
                                   quint8 white, quint8 amber, quint8 uv);

    /**
     * @brief setFixtureCapabilities
     * @param fxID the Fixture unique ID
     * @param enable used to increment/decrement the UI tools counters
     * @return A multihash containg the fixture capabilities by channel type
     */
    QMultiHash<int, SceneValue> setFixtureCapabilities(quint32 fxID, bool enable);

    int fixturesCount();
    QQmlListProperty<Fixture> fixtures();

signals:
    void docLoaded();
    void fixturesCountChanged();
    void newFixtureCreated(quint32 fxID, qreal x, qreal y);
    void channelValueChanged(quint32 fixtureID, quint32 channelIndex, quint8 value);
    void channelTypeValueChanged(int type, quint8 value);
    void colorChanged(QColor rgb, QColor wauv);

private:
    /** Reference to the QML view root */
    QQuickView *m_view;
    /** Reference to the project workspace */
    Doc *m_doc;
    /** List of the current Fixtures in Doc */
    QList<Fixture *> m_fixtureList;
};

#endif // FIXTUREMANAGER_H


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Support.V4.App;
using Android.Views;
using Android.Widget;
using Java.Lang;

namespace Android.Utilities
{
    public class TabFragmentsAdapter : FragmentPagerAdapter
    {
        public override int Count
        {
            get
            {
                return fragments.Length;
            }
        }

        private TabFragment[] fragments;

        public TabFragmentsAdapter(FragmentManager fragmentManager, params TabFragment[] fragments) : base(fragmentManager)
        {
            this.fragments = fragments;
        }

        public override Fragment GetItem(int position)
        {
            return fragments[position];
        }
        public override ICharSequence GetPageTitleFormatted(int position)
        {
            return new Java.Lang.String(fragments[position].Title);
        }
    }
}


text: package ${package}.repositories;


text:
import functools
import hashlib
from datetime import datetime

import blog.db as db

class Post():
    _FIELDS = ('body', 'title', 'author')
    _HASH_FIELDS = _FIELDS + ('timestamp',)
    _ALL_FIELDS = _HASH_FIELDS + ('id',)

    def __init__(self, kvp):
        for field in Post._FIELDS:
            if field not in kvp:
                self.valid = False
                return
            setattr(self, field, kvp[field])
        self.valid = True
        self.timestamp = kvp.get('timestamp', datetime.now())
        self.id = kvp.get('id', self._hash()[:16])

    def __iter__(self):
        for field in Post._ALL_FIELDS:
            yield field, getattr(self, field)

    def _hash(self):
        ''' Compute a hash of the current object. '''
        hasher = hashlib.sha256()
        for field in Post._HASH_FIELDS:
            hasher.update(str(getattr(self, field)).encode())
        return hasher.hexdigest()

def toPost(func):
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        postData = func(*args, **kwargs)
        return Post(postData) if postData is not None else None
    return wrapper

@toPost
def previousPost(post):
    ''' Return the post immediately before this one. '''
    return db.posts.find_one({'timestamp': {'$lt': post.timestamp}},
                             sort=[('timestamp', -1)])

@toPost
def nextPost(post):
    ''' Return the post immediately after this one, if any. '''
    return db.posts.find_one({'timestamp': {'$gt': post.timestamp}},
                             sort=[('timestamp', 1)])

@toPost
def retrieve(id):
    ''' Retrieve post with given id. '''
    return db.posts.find_one({'id': id})

def create(post):
    return db.posts.insert(dict(post))


text:
#include "as.h"
#include "subsegs.h"
#include "symcat.h"
#include "opcodes/ip2k-desc.h"
#include "opcodes/ip2k-opc.h"
#include "cgen.h"
#include "elf/common.h"
#include "elf/ip2k.h"
#include "libbfd.h"

/* Structure to hold all of the different components describing
   an individual instruction.  */
typedef struct
{
  const CGEN_INSN *	insn;
  const CGEN_INSN *	orig_insn;
  CGEN_FIELDS		fields;
#if CGEN_INT_INSN_P
  CGEN_INSN_INT         buffer [1];
#define INSN_VALUE(buf) (*(buf))
#else
  unsigned char         buffer [CGEN_MAX_INSN_SIZE];
#define INSN_VALUE(buf) (buf)
#endif
  char *		addr;
  fragS *		frag;
  int                   num_fixups;
  fixS *                fixups [GAS_CGEN_MAX_FIXUPS];
  int                   indices [MAX_OPERAND_INSTANCES];
}
ip2k_insn;

const char comment_chars[]        = ";";
const char line_comment_chars[]   = "#";
const char line_separator_chars[] = "";
const char EXP_CHARS[]            = "eE";
const char FLT_CHARS[]            = "dD";

/* Flag to detect when switching to code section where insn alignment is
   implied.  */
static int force_code_align = 0;

/* Mach selected from command line.  */
static int ip2k_mach = 0;
static unsigned ip2k_mach_bitmask = 0;

static void
ip2k_elf_section_rtn (int i)
{
  obj_elf_section(i);

  if (force_code_align)
    {
      /* The s_align_ptwo function expects that we are just after a .align
	 directive and it will either try and read the align value or stop
	 if end of line so we must fake it out so it thinks we are at the
	 end of the line.  */
      char *old_input_line_pointer = input_line_pointer;
      input_line_pointer = "\n";
      s_align_ptwo (1);
      force_code_align = 0;
      /* Restore.  */
      input_line_pointer = old_input_line_pointer;
    }
}

static void
ip2k_elf_section_text (int i)
{
  char *old_input_line_pointer;
  obj_elf_text(i);

  /* the s_align_ptwo function expects that we are just after a .align
     directive and it will either try and read the align value or stop if
     end of line so we must fake it out so it thinks we are at the end of
     the line.  */
  old_input_line_pointer = input_line_pointer;
  input_line_pointer = "\n";
  s_align_ptwo (1);
  force_code_align = 0;
  /* Restore.  */
  input_line_pointer = old_input_line_pointer;
}

/* The target specific pseudo-ops which we support.  */
const pseudo_typeS md_pseudo_table[] =
{
    { "text",   ip2k_elf_section_text,  0 },
    { "sect",   ip2k_elf_section_rtn,   0 },
    { NULL, 	NULL,			0 }
};

enum options
{
  OPTION_CPU_IP2022 = OPTION_MD_BASE,
  OPTION_CPU_IP2022EXT
};

struct option md_longopts[] =
{
  { "mip2022",     no_argument, NULL, OPTION_CPU_IP2022 },
  { "mip2022ext",  no_argument, NULL, OPTION_CPU_IP2022EXT },
  { NULL,           no_argument, NULL, 0 },
};
size_t md_longopts_size = sizeof (md_longopts);

const char * md_shortopts = "";

int
md_parse_option (int c ATTRIBUTE_UNUSED, char * arg ATTRIBUTE_UNUSED)
{
  switch (c)
    {
    case OPTION_CPU_IP2022:
      ip2k_mach = bfd_mach_ip2022;
      ip2k_mach_bitmask = 1 << MACH_IP2022;
      break;

    case OPTION_CPU_IP2022EXT:
      ip2k_mach = bfd_mach_ip2022ext;
      ip2k_mach_bitmask = 1 << MACH_IP2022EXT;
      break;

    default:
      return 0;
    }

  return 1;
}

void
md_show_usage (FILE * stream)
{
  fprintf (stream, _("IP2K specific command line options:\n"));
  fprintf (stream, _("  -mip2022               restrict to IP2022 insns \n"));
  fprintf (stream, _("  -mip2022ext            permit extended IP2022 insn\n"));
}

void
md_begin (void)
{
  /* Initialize the `cgen' interface.  */

  /* Set the machine number and endian.  */
  gas_cgen_cpu_desc = ip2k_cgen_cpu_open (CGEN_CPU_OPEN_MACHS,
					  ip2k_mach_bitmask,
					  CGEN_CPU_OPEN_ENDIAN,
					  CGEN_ENDIAN_BIG,
					  CGEN_CPU_OPEN_END);
  ip2k_cgen_init_asm (gas_cgen_cpu_desc);

  /* This is a callback from cgen to gas to parse operands.  */
  cgen_set_parse_operand_fn (gas_cgen_cpu_desc, gas_cgen_parse_operand);

  /* Set the machine type.  */
  bfd_default_set_arch_mach (stdoutput, bfd_arch_ip2k, ip2k_mach);
}

void
md_assemble (char * str)
{
  ip2k_insn insn;
  char * errmsg;

  /* Initialize GAS's cgen interface for a new instruction.  */
  gas_cgen_init_parse ();

  insn.insn = ip2k_cgen_assemble_insn
      (gas_cgen_cpu_desc, str, & insn.fields, insn.buffer, & errmsg);

  if (!insn.insn)
    {
      as_bad ("%s", errmsg);
      return;
    }

  /* Check for special relocation required by SKIP instructions.  */
  if (CGEN_INSN_ATTR_VALUE (insn.insn, CGEN_INSN_SKIPA))
    /* Unconditional skip has a 1-bit relocation of the current pc, so
       that we emit either sb pcl.0 or snb pcl.0 depending on whether
       the PCL (pc + 2) >> 1 is odd or even.  */
    {
      enum cgen_parse_operand_result result_type;
      bfd_vma value;
      const char *curpc_plus_2 = ".+2";
      const char *err;

      err = cgen_parse_address (gas_cgen_cpu_desc, & curpc_plus_2,
				IP2K_OPERAND_ADDR16CJP,
				BFD_RELOC_IP2K_PC_SKIP,
				& result_type, & value);
      if (err)
	{
	  as_bad ("%s", err);
	  return;
	}
    }

  /* Doesn't really matter what we pass for RELAX_P here.  */
  gas_cgen_finish_insn (insn.insn, insn.buffer,
			CGEN_FIELDS_BITSIZE (& insn.fields), 1, NULL);
}

valueT
md_section_align (segT segment, valueT size)
{
  int align = bfd_get_section_alignment (stdoutput, segment);

  return ((size + (1 << align) - 1) & (-1 << align));
}

symbolS *
md_undefined_symbol (char * name ATTRIBUTE_UNUSED)
{
    return 0;
}

int
md_estimate_size_before_relax (fragS * fragP ATTRIBUTE_UNUSED,
			       segT    segment ATTRIBUTE_UNUSED)
{
  as_fatal (_("relaxation not supported\n"));
  return 1;
}

/* *fragP has been relaxed to its final size, and now needs to have
   the bytes inside it modified to conform to the new size.

   Called after relaxation is finished.
   fragP->fr_type == rs_machine_dependent.
   fragP->fr_subtype is the subtype of what the address relaxed to.  */

void
md_convert_frag (bfd   * abfd  ATTRIBUTE_UNUSED,
		 segT    sec   ATTRIBUTE_UNUSED,
		 fragS * fragP ATTRIBUTE_UNUSED)
{
}

/* Functions concerning relocs.  */

long
md_pcrel_from (fixS *fixP ATTRIBUTE_UNUSED)
{
  abort ();
}

/* Return the bfd reloc type for OPERAND of INSN at fixup FIXP.
   Returns BFD_RELOC_NONE if no reloc type can be found.
   *FIXP may be modified if desired.  */

bfd_reloc_code_real_type
md_cgen_lookup_reloc (const CGEN_INSN *    insn     ATTRIBUTE_UNUSED,
		      const CGEN_OPERAND * operand,
		      fixS *               fixP     ATTRIBUTE_UNUSED)
{
  bfd_reloc_code_real_type result;

  result = BFD_RELOC_NONE;

  switch (operand->type)
    {
    case IP2K_OPERAND_FR:
    case IP2K_OPERAND_ADDR16L:
    case IP2K_OPERAND_ADDR16H:
    case IP2K_OPERAND_LIT8:
      /* These may have been processed at parse time.  */
      if (fixP->fx_cgen.opinfo != 0)
	result = fixP->fx_cgen.opinfo;
      fixP->fx_no_overflow = 1;
      break;

    case IP2K_OPERAND_ADDR16CJP:
      result = fixP->fx_cgen.opinfo;
      if (result == 0 || result == BFD_RELOC_NONE)
	result = BFD_RELOC_IP2K_ADDR16CJP;
      fixP->fx_no_overflow = 1;
      break;

    case IP2K_OPERAND_ADDR16P:
      result = BFD_RELOC_IP2K_PAGE3;
      fixP->fx_no_overflow = 1;
      break;

    default:
      result = BFD_RELOC_NONE;
      break;
    }

  return result;
}

/* Write a value out to the object file, using the appropriate endianness.  */

void
md_number_to_chars (char * buf, valueT val, int n)
{
  number_to_chars_bigendian (buf, val, n);
}

char *
md_atof (int type, char * litP, int *  sizeP)
{
  return ieee_md_atof (type, litP, sizeP, TRUE);
}

/* See whether we need to force a relocation into the output file.
   Force most of them, since the linker's bfd relocation engine
   understands range limits better than gas' cgen fixup engine.
   Consider the case of a fixup intermediate value being larger than
   the instruction it will be eventually encoded within.  */

int
ip2k_force_relocation (fixS * fix)
{
  switch (fix->fx_r_type)
    {
    case BFD_RELOC_IP2K_FR9:
    case BFD_RELOC_IP2K_FR_OFFSET:
    case BFD_RELOC_IP2K_BANK:
    case BFD_RELOC_IP2K_ADDR16CJP:
    case BFD_RELOC_IP2K_PAGE3:
    case BFD_RELOC_IP2K_LO8DATA:
    case BFD_RELOC_IP2K_HI8DATA:
    case BFD_RELOC_IP2K_EX8DATA:
    case BFD_RELOC_IP2K_LO8INSN:
    case BFD_RELOC_IP2K_HI8INSN:
    case BFD_RELOC_IP2K_PC_SKIP:
    case BFD_RELOC_IP2K_TEXT:
      return 1;

    case BFD_RELOC_16:
      if (fix->fx_subsy && S_IS_DEFINED (fix->fx_subsy)
	  && fix->fx_addsy && S_IS_DEFINED (fix->fx_addsy)
	  && (S_GET_SEGMENT (fix->fx_addsy)->flags & SEC_CODE))
	{
	  fix->fx_r_type = BFD_RELOC_IP2K_TEXT;
	  return 0;
	}
      break;

    default:
      break;
    }

  return generic_force_reloc (fix);
}

void
ip2k_apply_fix (fixS *fixP, valueT *valueP, segT seg)
{
  if (fixP->fx_r_type == BFD_RELOC_IP2K_TEXT
      && ! fixP->fx_addsy
      && ! fixP->fx_subsy)
    {
      *valueP = ((int)(* valueP)) / 2;
      fixP->fx_r_type = BFD_RELOC_16;
    }
  else if (fixP->fx_r_type == BFD_RELOC_UNUSED + IP2K_OPERAND_FR)
    {
      /* Must be careful when we are fixing up an FR.  We could be
	 fixing up an offset to (SP) or (DP) in which case we don't
	 want to step on the top 2 bits of the FR operand.  The
	 gas_cgen_md_apply_fix doesn't know any better and overwrites
	 the entire operand.  We counter this by adding the bits
	 to the new value.  */
      char *where = fixP->fx_frag->fr_literal + fixP->fx_where;

      /* Canonical name, since used a lot.  */
      CGEN_CPU_DESC cd = gas_cgen_cpu_desc;
      CGEN_INSN_INT insn_value
	= cgen_get_insn_value (cd, (unsigned char *) where,
			       CGEN_INSN_BITSIZE (fixP->fx_cgen.insn));
      /* Preserve (DP) or (SP) specification.  */
      *valueP += (insn_value & 0x180);
    }

  gas_cgen_md_apply_fix (fixP, valueP, seg);
}

int
ip2k_elf_section_flags (flagword flags,
			bfd_vma attr ATTRIBUTE_UNUSED,
			int type ATTRIBUTE_UNUSED)
{
  /* This is used to detect when the section changes to an executable section.
     This function is called by the elf section processing.  When we note an
     executable section specifier we set an internal flag to denote when
     word alignment should be forced.  */
  if (flags & SEC_CODE)
    force_code_align = 1;

  return flags;
}


text:
import sys

def parseMaps(goodMapFile, badMapFile):
    with open(goodMapFile) as gmf:
        goodMap = gmf.readlines()
        del goodMap[0]

    with open(badMapFile) as bmf:
        badMap = bmf.readlines()
        del badMap[0]

    bcMap = {}

# create a map from the sample ID to the good barcode
    for line in goodMap:
        line = line.split('\t')
        bcMap[line[0]] = line[1]

    for line in badMap:
        line = line.split('\t')
        if line[0] in bcMap:
            bcMap[line[0]] = (line[1], bcMap[line[0]])

return dict([t for t in bcMap.values() if isinstance(t, tuple)])

if __name__ == '__main__':
    goodMapFile = sys.argv[1]
    badMapFile = sys.argv[2]
    fastaFile = sys.argv[3]

    bcMap = parseMaps(goodMapFile, badMapFile)

    newFasta = open('new.fasta', 'w')

    with open(fastaFile) as f:
        for line in f:
            if line[0] == '>':
                header = line
                newFasta.write(header)
            else:
                # sequence info
                seq = line
                badCode = seq[:8]
                if badCode in bcMap:
                    newFasta.write(bcMap[badCode] + seq[8:])
                else:
                    print 'Mapping error: ' + header

    newFasta.close()


text:
#region LICENSE

//  Copyright 2016 Vitalii Zakharov (Lewis945)
//
//  Licensed under the Apache License, Version 2.0 (the "License"); you may not use this
//  file except in compliance with the License. You may obtain a copy of the License at
//
//    http://www.apache.org/licenses/LICENSE-2.0
//
//  Unless required by applicable law or agreed to in writing, software distributed under the License is
//  distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//  See the License for the specific language governing permissions and limitations under the License.

#endregion

namespace ScratchEngine.Math.Interfaces
{
    /// <summary>
    /// Defines a generalized method that a value type or class implements to create
    /// a type-specific method for determining division of instances.
    /// </summary>
    /// <typeparam name="T">The type of objects to divide by.</typeparam>
    public interface IDivision<T>
    {
        /// <summary>
        /// Divides this object by <see cref="T"/> object.
        /// </summary>
        /// <param name="other">An object to divide by.</param>
        /// <returns>New object that is product of division.</returns>
        T Divide(T other);
    }
}


text:
ssl_certificate CHANGELOG
=========================

This file is used to list changes made in each version of the `ssl_certificate` cookbook.

## 0.1.0:

* Initial release of `ssl_certificate`


text:
local storyboard = require( "storyboard" )
local scene = storyboard.newScene()

local widget = require 'widget'
local _W = display.contentWidth
local _H = display.contentHeight
local otherSoundEffect = require 'gameLogic.otherSoundEffect'
local soundEffect

-- Called when the scene's view does not exist:
function scene:createScene( event )
    local group = self.view

    soundEffect = otherSoundEffect.new()

    local backgroundImage = display.newImageRect("images/mainscreen.png", display.contentWidth, display.contentHeight)
    backgroundImage.x = display.contentCenterX
    backgroundImage.y = display.contentCenterY
    group:insert(backgroundImage)

    local function startButtonListener(event)
        if event.phase == "ended" then
            soundEffect:play("button")
            storyboard.gotoScene("login-scene", "fade", 800)
        end
    end
    local startButton = widget.newButton{
        defaultFile = "images/buttons/buttonStart.png",
        overFile = "images/buttons/buttonStartonclick.png",
        onEvent = startButtonListener,
    }
    startButton.anchorX, startButton.anchorY = .5, .5
    startButton.x = display.contentCenterX
    startButton.y = 405
    group:insert(startButton)

end

-- Called BEFORE scene has moved onscreen:
function scene:willEnterScene( event )
    local group = self.view

end

-- Called immediately after scene has moved onscreen:
function scene:enterScene( event )
    local group = self.view

    local BGM = require 'gameLogic.backgroundMusic'
    BGM.play("main")

end

-- Called when scene is about to move offscreen:
function scene:exitScene( event )
    local group = self.view

end

-- Called AFTER scene has finished moving offscreen:
function scene:didExitScene( event )
    local group = self.view
    soundEffect:dispose()
    soundEffect = nil
end

-- Called prior to the removal of scene's "view" (display group)
function scene:destroyScene( event )
    local group = self.view
    group:removeSelf()
    group = nil
end

-- Called if/when overlay scene is displayed via storyboard.showOverlay()
function scene:overlayBegan( event )
    local group = self.view
    local overlay_name = event.sceneName  -- name of the overlay scene

end

-- Called if/when overlay scene is hidden/removed via storyboard.hideOverlay()
function scene:overlayEnded( event )
    local group = self.view
    local overlay_name = event.sceneName  -- name of the overlay scene

end

---------------------------------------------------------------------------------
-- END OF YOUR IMPLEMENTATION
---------------------------------------------------------------------------------
-- "createScene" event is dispatched if scene's view does not exist
scene:addEventListener( "createScene", scene )
-- "willEnterScene" event is dispatched before scene transition begins
scene:addEventListener( "willEnterScene", scene )
-- "enterScene" event is dispatched whenever scene transition has finished
scene:addEventListener( "enterScene", scene )
-- "exitScene" event is dispatched before next scene's transition begins
scene:addEventListener( "exitScene", scene )
-- "didExitScene" event is dispatched after scene has finished transitioning out
scene:addEventListener( "didExitScene", scene )
-- "destroyScene" event is dispatched before view is unloaded, which can be
-- automatically unloaded in low memory situations, or explicitly via a call to
-- storyboard.purgeScene() or storyboard.removeScene().
scene:addEventListener( "destroyScene", scene )
-- "overlayBegan" event is dispatched when an overlay scene is shown
scene:addEventListener( "overlayBegan", scene )
-- "overlayEnded" event is dispatched when an overlay scene is hidden/removed
scene:addEventListener( "overlayEnded", scene )
---------------------------------------------------------------------------------

return scene


text:
#ifndef HEADER_8E9D0ABA3C76B989
#define HEADER_8E9D0ABA3C76B989

#ifndef MAT3_H_INCLUDED
#define MAT3_H_INCLUDED

#include "CCPlatformMacros.h"

#include "utility.h"

struct kmVec3;
struct kmQuaternion;
struct kmMat4;

typedef struct kmMat3{
	kmScalar mat[9];
} kmMat3;

#ifdef __cplusplus
extern "C" {
#endif

CC_DLL kmMat3* kmMat3Fill(kmMat3* pOut, const kmScalar* pMat);
CC_DLL kmMat3* kmMat3Adjugate(kmMat3* pOut, const kmMat3* pIn);
CC_DLL kmMat3* kmMat3Identity(kmMat3* pOut);
CC_DLL kmMat3* kmMat3Inverse(kmMat3* pOut, const kmMat3* pM);
CC_DLL int  kmMat3IsIdentity(const kmMat3* pIn);
CC_DLL kmMat3* kmMat3Transpose(kmMat3* pOut, const kmMat3* pIn);
CC_DLL kmScalar kmMat3Determinant(const kmMat3* pIn);
CC_DLL kmMat3* kmMat3Multiply(kmMat3* pOut, const kmMat3* pM1, const kmMat3* pM2);
CC_DLL kmMat3* kmMat3ScalarMultiply(kmMat3* pOut, const kmMat3* pM, const kmScalar pFactor);

CC_DLL kmMat3* kmMat3Assign(kmMat3* pOut, const kmMat3* pIn);
CC_DLL kmMat3* kmMat3AssignMat4(kmMat3* pOut, const struct kmMat4* pIn);
CC_DLL int  kmMat3AreEqual(const kmMat3* pM1, const kmMat3* pM2);

CC_DLL struct kmVec3* kmMat3GetUpVec3(struct kmVec3* pOut, const kmMat3* pIn);
CC_DLL struct kmVec3* kmMat3GetRightVec3(struct kmVec3* pOut, const kmMat3* pIn);
CC_DLL struct kmVec3* kmMat3GetForwardVec3(struct kmVec3* pOut, const kmMat3* pIn);

CC_DLL kmMat3* kmMat3RotationX(kmMat3* pOut, const kmScalar radians);
CC_DLL kmMat3* kmMat3RotationY(kmMat3* pOut, const kmScalar radians);
CC_DLL kmMat3* kmMat3RotationZ(kmMat3* pOut, const kmScalar radians);

CC_DLL kmMat3* kmMat3Rotation(kmMat3* pOut, const kmScalar radians);
CC_DLL kmMat3* kmMat3Scaling(kmMat3* pOut, const kmScalar x, const kmScalar y);
CC_DLL kmMat3* kmMat3Translation(kmMat3* pOut, const kmScalar x, const kmScalar y);

CC_DLL kmMat3* kmMat3RotationQuaternion(kmMat3* pOut, const struct kmQuaternion* pIn);

CC_DLL kmMat3* kmMat3RotationAxisAngle(kmMat3* pOut, const struct kmVec3* axis, kmScalar radians);
CC_DLL struct kmVec3* kmMat3RotationToAxisAngle(struct kmVec3* pAxis, kmScalar* radians, const kmMat3* pIn);
CC_DLL kmMat3* kmMat3LookAt(kmMat3* pOut, const struct kmVec3* pEye, const struct kmVec3* pCenter, const struct kmVec3* pUp);

#ifdef __cplusplus
}
#endif
#endif // MAT3_H_INCLUDED

#endif // header guard


text:
package com.vmware.spring.workshop.services.facade.impl;

import java.util.Collection;

import javax.inject.Inject;

import org.apache.commons.collections.CollectionUtils;
import org.junit.Assert;
import org.junit.Test;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.ContextConfiguration;

import com.vmware.spring.workshop.dto.user.UserDTO;
import com.vmware.spring.workshop.dto.user.UserRoleTypeDTO;
import com.vmware.spring.workshop.services.AbstractServicesTestSupport;
import com.vmware.spring.workshop.services.facade.AbstractFacadeTestSupport;
import com.vmware.spring.workshop.services.facade.FacadeValueFinder;
import com.vmware.spring.workshop.services.facade.UsersFacade;

/**
 * @author lgoldstein
 */
@ContextConfiguration(locations={ AbstractServicesTestSupport.DEFAULT_TEST_CONTEXT })
@ActiveProfiles("hibernate")
public class UsersFacadeImplTest extends AbstractFacadeTestSupport {
    @Inject private UsersFacade    _usrFacade;

    public UsersFacadeImplTest() {
        super();
    }

    @Test
    public void testFindByLoginName () {
        runFacadeValueFinderTest(new FacadeValueFinder<UsersFacade,UserDTO>() {
                @Override
                public UserDTO findDtoValue(UsersFacade facade, UserDTO dto) {
                    return facade.findByLoginName(dto.getLoginName());
                }
            });
    }

    @Test
    public void testFindById () {
        runFacadeValueFinderTest(new FacadeValueFinder<UsersFacade,UserDTO>() {
                @Override
                public UserDTO findDtoValue(UsersFacade facade, UserDTO dto) {
                    return facade.findById(dto.getId());
                }
            });
    }

    @Test
    public void testInternalUserAuthentication () {
        final Collection<? extends UserDTO>    dtoList=_usrFacade.findAll();
        Assert.assertFalse("No current users", CollectionUtils.isEmpty(dtoList));

        for (final UserDTO dto : dtoList) {
            final Authentication    authData=new UsernamePasswordAuthenticationToken(dto.getLoginName(), dto.getPassword()),
                                    authResult=_usrFacade.authenticate(authData);
            Assert.assertNotNull("No authentication result for " + dto, authResult);

            final Object    principal=authResult.getPrincipal();
            Assert.assertTrue("Principal not UserDTO for " + dto, principal instanceof UserDTO);
            Assert.assertEquals("Mismatched principal values", dto, principal);

            final Collection<? extends GrantedAuthority>    gaList=authResult.getAuthorities();
            Assert.assertFalse("No authorities for " + dto, CollectionUtils.isEmpty(gaList));
            Assert.assertEquals("Mismatched size of authorities for " + dto, 1, gaList.size());

            final GrantedAuthority    ga=gaList.iterator().next();
            final UserRoleTypeDTO    role=dto.getRole();
            Assert.assertEquals("Mismatched granted authority for " + dto, role.name(), ga.getAuthority());
        }
    }

    private void runFacadeValueFinderTest (final FacadeValueFinder<UsersFacade,UserDTO> finder) {
        runFacadeValueFinderTest(_usrFacade, _usrFacade.findAll(), finder);
    }
}


text:
"""
Plugin for probing ftp
"""
from owtf.managers.resource import get_resources
from owtf.plugin.helper import plugin_helper

DESCRIPTION = " FTP Probing "

def run(PluginInfo):
    resource = get_resources("FtpProbeMethods")
    # No previous output
    return plugin_helper.CommandDump("Test Command", "Output", resource, PluginInfo, [])


text:
var async = require('async')

var parsing = require('./parsing')
var build = require('./build')
var prepare = require('./prepare')
var access = require('./access')

exports.prepareControlRepository = function (toolbelt, callback) {
  async.parallel([
    assetHandler(toolbelt),
    grantControlRepoAccess(toolbelt),
    contentRepositoryListHandler(toolbelt)
  ], callback)
}

var assetHandler = function (toolbelt) {
  return function (callback) {
    prepare.recursivelyPrepare(toolbelt, callback)
  }
}

var grantControlRepoAccess = function (toolbelt) {
  return function (callback) {
    access.grantUsersAccess(toolbelt, toolbelt.project.name, callback)
  }
}

var contentRepositoryListHandler = function (toolbelt) {
  return function (callback) {
    parsing.controlRepoList(toolbelt, function (err, list) {
      if (err) {
        if (err.code === 'ENOENT') {
          toolbelt.info('No content-repositories.json file found.')
          toolbelt.info('Skipping control repository build setup.')

          return callback(null)
        }

        return callback(err)
      }

      toolbelt.info('Configuring %s builds.', list.length)

      async.map(list, async.apply(build.create, toolbelt), callback)
    })
  }
}


text:
Object.defineProperty(document, 'hidden', {
  value: false,
});


text:
import { IMessagePassingProtocol } from 'vs/base/parts/ipc/common/ipc';
import { Event } from 'vs/base/common/event';
import { VSBuffer } from 'vs/base/common/buffer';

export interface Sender {
	send(channel: string, msg: unknown): void;
}

/**
 * The Electron `Protocol` leverages Electron style IPC communication (`ipcRenderer`, `ipcMain`)
 * for the implementation of the `IMessagePassingProtocol`. That style of API requires a channel
 * name for sending data.
 */
export class Protocol implements IMessagePassingProtocol {

	constructor(private sender: Sender, readonly onMessage: Event<VSBuffer>) { }

	send(message: VSBuffer): void {
		try {
			this.sender.send('vscode:message', message.buffer);
		} catch (e) {
			// systems are going down
		}
	}

	disconnect(): void {
		this.sender.send('vscode:disconnect', null);
	}
}


text:
//
//  CCStoreAssetsBuilder.h
//  Pods
//
//  Created by Le Van Kiet on 9/12/18.
//

#ifndef CCStoreAssetsBuilder_h
#define CCStoreAssetsBuilder_h

#ifdef __cplusplus

#include "soomla/CCStoreAssets.h"

namespace soomla {

class CCVirtualCurrency;
class CCVirtualGood;
class CCVirtualCurrencyPack;
class CCVirtualCategory;

class CCStoreAssetsBuilder {
    using Self = CCStoreAssetsBuilder;

public:
    class StoreAssets : public soomla::CCStoreAssets {
    public:
        virtual std::int32_t getVersion() override;
        /**
        @see parent
        */
        virtual cocos2d::Vector<soomla::CCVirtualCurrency*>&
        getCurrencies() override;

        /**
        @see parent
        */
        virtual cocos2d::Vector<soomla::CCVirtualGood*>& getGoods() override;

        /**
        @see parent
        */
        virtual cocos2d::Vector<soomla::CCVirtualCurrencyPack*>&
        getCurrencyPacks() override;

        /**
        @see parent
        */
        virtual cocos2d::Vector<soomla::CCVirtualCategory*>&
        getCategories() override;

    public:
        cocos2d::Vector<soomla::CCVirtualCurrency*> currencies_;
        cocos2d::Vector<soomla::CCVirtualGood*> goods_;
        cocos2d::Vector<soomla::CCVirtualCurrencyPack*> currencyPacks_;
        cocos2d::Vector<soomla::CCVirtualCategory*> categories_;
        std::int32_t version_;
    };

    CCStoreAssetsBuilder();

    Self& setVersion(std::int32_t version);

    Self& addCurrency(soomla::CCVirtualCurrency* currency);

    Self& addGood(soomla::CCVirtualGood* good);

    Self& addCurrencyPack(soomla::CCVirtualCurrencyPack* pack);

    Self& addCategorie(soomla::CCVirtualCategory* category);

    soomla::CCStoreAssets* build();

private:
    cocos2d::RefPtr<StoreAssets> storeAssets_;
};
} // namespace soomla

#endif // __cplusplus

#endif /* CCStoreAssetsBuilder_h */


text:
template <typename T>
using test_flex_vector_t =
    immer::flex_vector<T, immer::default_memory_policy, 3u, 0u>;

template <typename T>
using test_vector_t =
    immer::vector<T, immer::default_memory_policy, 3u, 0u>;

#define FLEX_VECTOR_T test_flex_vector_t
#define VECTOR_T      test_vector_t
#include "generic.ipp"


text:
/**
 *	MarkerPolygon - additional component for HereMaps
 *	@author: Andre Rodrigues (andrecr12@hotmail.com)
 *
 */

var MarkerPolygon = function (display, $container, props) {
	// Call the "super" constructor to initialize properties inherited from Container
	nokia.maps.map.Container.call(this);

	// Calling MarkerPolygon constructor
	this.init(display, $container, props);
};

// MarkerPolygon constructor function
MarkerPolygon.prototype.init = function (display, map, props) {
	this.display = display;
	this.map = map;
	this.lineProps = props.polygon;
	this.markerProps = props.marker;
	this.editingIndex = -1;
	this.markerRadius = 5;
	this.markersAlpha = '0.6';
	this.editable = true;

	/*	Fix this */
	this.divDraggable = this.map.find('div[draggable="true"][aria-role!="button"]');

	this.xyCoords = [];

	//create canvas element
	this.canvas = $('<canvas>');
	var zindexAux = parseInt( this.map.css('z-index'), 10 ) + 1;
	var topAux = this.map[0].offsetTop;
	var leftAux = this.map[0].offsetLeft;
	this.canvas.css({'position': 'absolute', 'display': 'none', 'z-index': zindexAux, 'top': topAux, 'left': leftAux});
	this.canvas.appendTo(this.map);

	this.canvasCtx = this.canvas[0].getContext("2d");
	this.canvasCtx.canvas.width = this.map.innerWidth();
	this.canvasCtx.canvas.height = this.map.innerHeight();

	this.editing = false;
	this.loading = false;
	this.autoClosePath = true;

	var self = this;
	$(document).mouseup(function(event) {
		if(self.editing){
			$(document).unbind('mousemove');
			self.updateMarkersCoordinates(event);
			//draw canvas polygon on map
			self.canvasToMap();
			self.editingIndex = -1;
			self.divDraggable.attr('draggable', 'true');
			self.editing = false;

			if(typeof self.onChangeHandler === 'function'){
				self.onChangeHandler(event);
			}
		}
	});
};
MarkerPolygon.prototype.canvasToMap = function () {
	var self = this;
	var newPath = [];
	for(var i in this.xyCoords){
		if(! this.xyCoords[i].editable){
			newPath.push(this.xyCoords[i].marker.coordinate);
		}
		this.xyCoords[i].marker.set("visibility", true);
	}
	this.Polygon.set('path', newPath);
	this.Polygon.set("visibility", true);
	setTimeout(function(){self.canvas.css('display', 'none');}, 300);
};
MarkerPolygon.prototype.add = function (vertex) {
	//if(this.xyCoords.length < 6){
		var self = this;

		var coord;		//keeps new vertex as nokia.maps.geo.Coordinate (lat, lng)
		var point;		//keeps new vertex as nokia.maps.util.Point (x, y)
		if(vertex.x && vertex.y){
			coord = this.display.pixelToGeo(vertex.x, vertex.y);
			point = vertex;
		} else if(vertex.lat && vertex.lng){
			coord = new nokia.maps.geo.Coordinate(vertex.lat, vertex.lng);
			point = this.display.geoToPixel(coord);
		} else {
			throw "Invalid format of new Vertex: "+ vertex;
		}

		var markerProps = this.markerProps;
		markerProps.icon = this.createIcon(false);
		markerProps.anchor = {x: 6, y: 6};
		markerProps.draggable = (this.loading) ? false : true;
		markerProps.visibility = (this.loading) ? false : true;

		var marker = new nokia.maps.map.Marker(coord, markerProps);

		this.xyCoords.push({ x: point.x, y: point.y, editable: false, marker: marker });

		// Add the listener function to the capturing phase of the "drag" event
		marker.addListener("mousedown", (this.clickMarker).bind(this), true);

		//changes on mouse cursor
		marker.addListener("mouseover", function (evt) { self.setCursor((self.editable) ? "pointer" : "default"); });
		marker.addListener("mouseout", function (evt) {	self.setCursor("default"); });

		this.display.objects.add(marker);

		if(! this.Polygon){
			this.Polygon = new nokia.maps.map.Polygon([coord], this.lineProps);
			this.display.objects.add(this.Polygon);
		} else{
			this.Polygon.path.add(coord);

			//create markers to modify the polygon/line
			if(this.xyCoords.length > 1){
				this.createEditableMarker(this.xyCoords.length-2, this.xyCoords.length-1);

				//closes the polygon if it has 5+ markers and it doesn't have any other marker to load
				if(this.xyCoords.length >= 5 && this.autoClosePath){
					this.createEditableMarker(this.xyCoords.length-1, 0);
				}
			}
		}
	//}
};
MarkerPolygon.prototype.drawCanvasPolygon = function(){
	this.canvasCtx.canvas.width = this.canvasCtx.canvas.width;

	//draw polygon without the markers
	this.canvasCtx.beginPath();
	for(var i in this.xyCoords){
		if(i === 0){
			this.canvasCtx.moveTo(this.xyCoords[i].x, this.xyCoords[i].y);
		} else{
			if(!this.xyCoords[i].editable){
				this.canvasCtx.lineTo(this.xyCoords[i].x, this.xyCoords[i].y);
			}
		}
	}
	this.canvasCtx.closePath();
	this.canvasCtx.fillStyle = this.lineProps.brush.color;
	this.canvasCtx.fill();
	this.canvasCtx.lineWidth = this.lineProps.pen.lineWidth;
	this.canvasCtx.strokeStyle = this.lineProps.pen.strokeColor;
	this.canvasCtx.stroke();

	//draw markers
	for(i in this.xyCoords){
		this.canvasCtx.moveTo(this.xyCoords[i].x, this.xyCoords[i].y);
		this.canvasCtx.beginPath();
		this.canvasCtx.arc(this.xyCoords[i].x, this.xyCoords[i].y, this.markerRadius, 0,2*Math.PI);
		this.canvasCtx.closePath();

		this.canvasCtx.fillStyle = (this.xyCoords[i].editable) ? 'rgba(255,255,255,'+ this.markersAlpha +')' : 'white';
		this.canvasCtx.fill();
		this.canvasCtx.strokeStyle = (this.xyCoords[i].editable) ? 'rgb(127,127,127)' : this.markerProps.brush.strokeColor;
		this.canvasCtx.stroke();
	}
};
MarkerPolygon.prototype.mapToCanvas = function() {
	//console.log("mapToCanvas: ", this, arguments);
	var self = this;
	for(var i in this.xyCoords){
		this.xyCoords[i].marker.set("visibility", false);
	}
	this.Polygon.set("visibility", false);
	setTimeout(function(){self.canvas.css('display', 'block');}, 250);
};
MarkerPolygon.prototype.clickMarker = function (evt) {
	//console.log("MarkerPolygon.clickMarker ", this, arguments);
	if(this.editable){
		var self = this;
		evt.preventDefault();
		this.divDraggable.attr('draggable', 'false');

		this.editing = true;

		//update coord(x,y) in case the map moved
		var coordAux;
		for(var i=0; i < this.xyCoords.length; i++){
			coordAux = this.display.geoToPixel( this.xyCoords[i].marker.coordinate );
			this.xyCoords[i].x = coordAux.x;
			this.xyCoords[i].y = coordAux.y;
			if(this.xyCoords[i].marker === evt.target){
				this.editingIndex = i;
				//transform editable Marker into vertex marker
				if(this.xyCoords[this.editingIndex].editable){
					this.xyCoords[this.editingIndex].editable = false;
					if(this.editingIndex+1 === this.xyCoords.length){
						this.createEditableMarker(this.editingIndex-1, this.editingIndex);
						this.createEditableMarker(this.editingIndex+1, 0);
					} else{
						this.createEditableMarker(this.editingIndex-1, this.editingIndex);
						this.createEditableMarker(this.editingIndex+1, this.editingIndex+2);
					}
				}
			}
		}
		this.mapToCanvas();
		$(document).mousemove((this.updateMarkersPositions).bind(this));
	}
};
MarkerPolygon.prototype.updateMarkersPositions = function(e){
	if(this.editingIndex === -1){
		console.error("Error on identifying marker was clicked");
	} else{
		var mainMarker = this.xyCoords[this.editingIndex];
		mainMarker.x = e.pageX - this.map.offset().left;
		mainMarker.y = e.pageY - this.map.offset().top;
		this.xyCoords[this.editingIndex] = mainMarker;

		if(this.xyCoords.length > 1){
			//update the left editable Marker
			var lFixedIndex = (this.xyCoords[this.editingIndex-2]) ? this.editingIndex-2 : this.xyCoords.length-2;
			var lEditIndex = (this.xyCoords[this.editingIndex-1]) ? this.editingIndex-1 : this.xyCoords.length-1;
			var leftMarker = this.xyCoords[lEditIndex];
			leftMarker.x = (mainMarker.x + this.xyCoords[lFixedIndex].x)/2;
			leftMarker.y = (mainMarker.y + this.xyCoords[lFixedIndex].y)/2;
			this.xyCoords[lEditIndex] = leftMarker;

			if(this.xyCoords.length > 3){
				//update the right editable Marker
				var rFixedIndex = (this.xyCoords[this.editingIndex+2]) ? this.editingIndex+2 : 0;
				var rEditIndex = (this.xyCoords[this.editingIndex+1]) ? this.editingIndex+1 : 0;
				var rightMarker = this.xyCoords[rEditIndex];
				rightMarker.x = (mainMarker.x + this.xyCoords[rFixedIndex].x)/2;
				rightMarker.y = (mainMarker.y + this.xyCoords[rFixedIndex].y)/2;
				this.xyCoords[rEditIndex] = rightMarker;
			}
		}
		this.drawCanvasPolygon();
	}
};
MarkerPolygon.prototype.updateMarkersCoordinates = function(event){
	//update main Marker (which is being dragged)
	var mainMarker = this.xyCoords[this.editingIndex];
	this.xyCoords[this.editingIndex].marker.coordinate = this.display.pixelToGeo(mainMarker.x, mainMarker.y);

	if(this.xyCoords.length > 1){
		//update the left editable Marker
		var lMarkerIndex = (this.xyCoords[this.editingIndex-1]) ? this.editingIndex-1 : this.xyCoords.length-1;
		var leftMarker = this.xyCoords[lMarkerIndex];

		this.xyCoords[lMarkerIndex].marker.coordinate = this.display.pixelToGeo(leftMarker.x, leftMarker.y);

		//update the right editable Marker
		if(this.xyCoords.length > 3){
			var rMarkerIndex = (this.xyCoords[this.editingIndex+1]) ? this.editingIndex+1 : 0;
			var rightMarker = this.xyCoords[rMarkerIndex];
			this.xyCoords[rMarkerIndex].marker.coordinate = this.display.pixelToGeo(rightMarker.x, rightMarker.y);
		}
	}
};
MarkerPolygon.prototype.createIcon = function(editable){
	var alpha = (editable) ? this.markersAlpha : '1.0';
	var strokeColor = (editable) ? '#888' : this.markerProps.brush.color;

	//circle: radius 5px, border 1px
	var svg = '<svg width="12" height="12" xmlns="http://www.w3.org/2000/svg" version="1.1">'+
				'<circle cx="6" cy="6" r="'+ this.markerRadius +'" stroke="'+ strokeColor +'" stroke-width="1" fill="white" fill-opacity="'+ alpha +'"/>'+
			  '</svg>';
	var svgParser = new nokia.maps.gfx.SvgParser();

	return new nokia.maps.gfx.GraphicsImage(svgParser.parseSvg(svg));
};
MarkerPolygon.prototype.destroy = function(){
	//var path = this.Polygon.path;
	for(var i=this.xyCoords.length-1; i >= 0; i--){
		this.display.objects.remove(this.xyCoords[i].marker);
		this.xyCoords.splice(i, 0);
	}
	this.xyCoords = [];
	if(this.Polygon){
		this.Polygon.destroy();
		this.Polygon = null;
	}
};
MarkerPolygon.prototype.createEditableMarker = function(index1, index2){
	var self = this;
	var point = {
		x: (this.xyCoords[index1].x + this.xyCoords[index2].x)/2,
		y: (this.xyCoords[index1].y + this.xyCoords[index2].y)/2
	};
	var coord = this.display.pixelToGeo(point.x, point.y);

	var markerProps = this.markerProps;
	markerProps.icon = this.createIcon(true);
	markerProps.anchor = {x: 6, y: 6};
	markerProps.draggable = (this.loading) ? false : true;
	markerProps.visibility = (this.loading) ? false : true;

	var marker = new nokia.maps.map.Marker(coord, markerProps);
	//marker.index = index;

	//insert in xyCoords maintaining the path order
	this.xyCoords.splice((index2 !== 0) ? index2 : this.xyCoords.length, 0, { x: point.x, y: point.y, editable: true, marker: marker});

	// Add the listener function to the capturing phase of the "drag" event
	marker.addListener("mousedown", (this.clickMarker).bind(this), true);

	//changes on mouse cursor
	marker.addListener("mouseover", function (evt) { self.setCursor((self.editable) ? "pointer" : "default"); });
	marker.addListener("mouseout", function (evt) {	self.setCursor("default"); });

	/* Add the marker to the object's collections
	 * so the marker will be rendered onto the map
	 */
	this.display.objects.add(marker);
};
MarkerPolygon.prototype.transformMarker = function(evt){
	//console.log("MarkerPolygon.transformMarker ", this, arguments);

	for(var i = 0; i < this.xyCoords.length; i++){
		if(this.xyCoords[i] === evt.target){
			this.editingIndex = i;
			if(i+1 === this.xyCoords.length){
				this.createEditableMarker(i-1, 0);
			} else {
				this.createEditableMarker(i-1, i+1);
			}
		}
	}
};
// Polygon containsLatLng - method to determine if a latLng is within a polygon
MarkerPolygon.prototype.containsLatLng = function(latLng) {
	var lat, lng;

	//arguments are a pair of lat, lng variables
	if(arguments.length === 2) {
		lat = (typeof arguments[0] === "number") ? arguments[0] : parseFloat(arguments[0]);
		lng = (typeof arguments[0] === "number") ? arguments[1] : parseFloat(arguments[1]);
	} else if (arguments.length === 1) {
		lat = latLng.latitude;
		lng = latLng.longitude;
	} else {
		console.error("Wrong number of inputs in MarkerPolygon.prototype.containsLatLng");
	}

	// Raycast point in polygon method
	var inPoly = false;
	var numPoints = this.xyCoords.length;
	var j = numPoints-1;

	for(var i=0; i < numPoints; i++) {
		var vertex1 = this.xyCoords[i].marker.coordinate;
		var vertex2 = this.xyCoords[j].marker.coordinate;

		if (vertex1.longitude < lng && vertex2.longitude >= lng || vertex2.longitude < lng && vertex1.longitude >= lng) {
			if (vertex1.latitude + (lng - vertex1.longitude) / (vertex2.longitude - vertex1.longitude) * (vertex2.latitude - vertex1.latitude) < lat) {
				inPoly = !inPoly;
			}
		}

		j = i;
	}
	return inPoly;
};
MarkerPolygon.prototype.setEditable = function(editable) {
	this.editable = editable;
	for(var i in this.xyCoords) {
		this.xyCoords[i].marker.set({
			'draggable': editable,
			'visibility': editable
		});
	}
};
MarkerPolygon.prototype.exists = function() {
	if(this.xyCoords.length > 0){
		return true;
	} else {
		return false;
	}
};
MarkerPolygon.prototype.closedPolygon = function() {
	if(this.xyCoords.length >= 6){
		return true;
	} else {
		return false;
	}
};
MarkerPolygon.prototype.onChange = function(handler) {
	this.onChangeHandler = handler;
};
MarkerPolygon.prototype.setCursor = function(cursor){
	window.document.body.style.cursor = cursor;
};

/*
 * Returns the markerPolygon in WKT format: "POLYGON((LNG LAT,LNG LAT, ...))"
 */
MarkerPolygon.prototype.getPolygonAsString = function(){
	var polygonStrg = '["((';
	//get all real vertexes (excluding the middle points) => i=i+2
	for(var i = 0; i < this.xyCoords.length; i = i+2){
		polygonStrg += this.xyCoords[i].marker.coordinate.longitude +" "+ this.xyCoords[i].marker.coordinate.latitude +",";
	}
	//include the first point in the end to close the polygon
	polygonStrg += this.xyCoords[0].marker.coordinate.longitude +" "+ this.xyCoords[0].marker.coordinate.latitude +'))"]';
	return polygonStrg;
};

MarkerPolygon.prototype.getPolygonPoints = function(){
	var points = [];
	//get all real vertexes (excluding the middle points) => i=i+2
	for(var i = 0; i < this.xyCoords.length; i = i+2){
		points.push({
			longitude: this.xyCoords[i].marker.coordinate.longitude,
			latitude: this.xyCoords[i].marker.coordinate.latitude
		});
	}
	return points;
};

/*
 * Loads a polygon from an Array of objects {latitude: XX, longitude: YY} and let it on a non-editable state
 * Returns a jQuery Deferred Promise, to execute a code after the complete creation of the polygon, that can be:
 *		- resolved (if successfully created);
 *		- rejected (in case of an exception)
 */
MarkerPolygon.prototype.loadPolygon = function(points){
	var self = this;

	self.loading = true;
	self.autoClosePath = false;

	var $def = $.Deferred();
	self.display.addListener('displayready', function(evt){
		try{
			for(var i = 0; i < points.length; i++){
				//alert method 'add' to close polygon
				if(i === points.length-1){
					self.autoClosePath = true;
				}
				//add point
				self.add({lat: points[i].latitude, lng: points[i].longitude});
			}
		} catch(e){
			console.error(e);
			$def.reject();
		} finally{
			self.loading = false;
			$def.resolve();
		}
	});
	return $def.promise();
};


text:
FROM debian:buster-slim AS dependency-base

ENV DEBIAN_FRONTEND noninteractive

RUN apt-get update \
	&& apt-get install -y \
	ca-certificates \
	tzdata \
	&& apt-get clean autoclean \
	&& apt-get autoremove --yes \
	&& rm -rf /var/lib/{apt,dpkg,cache,log}

# NOTE: We separate these two stages so we can run the above
# quickly in CI, in case of flaky failure.
FROM dependency-base

EXPOSE 8086

COPY influxd /usr/bin/
COPY docker/influxd/entrypoint.sh /entrypoint.sh

ENTRYPOINT ["/entrypoint.sh"]
CMD ["influxd"]


text:
prestashop-module
=========================

CHANGE LOG

v1.0.2.

* removed examples sdk
* added index to SDK
* updated licenses

v1.0.1.
17 / 11 / 2013

* added zones, countries, taxes and free above to shipping


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

<title>NetworkConnection.ConnectionType</title>
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

org.openqa.selenium.mobile

Class NetworkConnection.ConnectionType

java.lang.Object

org.openqa.selenium.mobile.NetworkConnection.ConnectionType

Enclosing interface:

NetworkConnection

public static class NetworkConnection.ConnectionType
extends java.lang.Object

ConnectionType is a bitmask to represent a device's network connection

 Data  | WIFI | Airplane
 0       0      1         == 1
 1       1      0         == 6
 1       0      0         == 4
 0       1      0         == 2
 0       0      0         == 0

Giving "Data" the first bit positions in order to give room for the future of enabling
 specific types of data (Edge / 2G, 3G, 4G, LTE, etc) if the device allows it.

Field Summary

Fields

Modifier and Type
Field and Description

static NetworkConnection.ConnectionType
AIRPLANE_MODE

static NetworkConnection.ConnectionType
ALL

static NetworkConnection.ConnectionType
DATA

static NetworkConnection.ConnectionType
NONE

static NetworkConnection.ConnectionType
WIFI

Constructor Summary

Constructors

Constructor and Description

NetworkConnection.ConnectionType(java.lang.Boolean wifi,
                                java.lang.Boolean data,
                                java.lang.Boolean airplaneMode)

NetworkConnection.ConnectionType(int mask)

Method Summary

Methods

Modifier and Type
Method and Description

boolean
equals(java.lang.Object type)

java.lang.Boolean
isAirplaneMode()

java.lang.Boolean
isDataEnabled()

java.lang.Boolean
isWifiEnabled()

java.lang.String
toString()

Methods inherited from class java.lang.Object

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

Field Detail

WIFI

public static final NetworkConnection.ConnectionType WIFI

DATA

public static final NetworkConnection.ConnectionType DATA

AIRPLANE_MODE

public static final NetworkConnection.ConnectionType AIRPLANE_MODE

ALL

public static final NetworkConnection.ConnectionType ALL

NONE

public static final NetworkConnection.ConnectionType NONE

Constructor Detail

NetworkConnection.ConnectionType

public NetworkConnection.ConnectionType(java.lang.Boolean wifi,
                                java.lang.Boolean data,
                                java.lang.Boolean airplaneMode)

NetworkConnection.ConnectionType

public NetworkConnection.ConnectionType(int mask)

Method Detail

isAirplaneMode

public java.lang.Boolean isAirplaneMode()

isWifiEnabled

public java.lang.Boolean isWifiEnabled()

isDataEnabled

public java.lang.Boolean isDataEnabled()

equals

public boolean equals(java.lang.Object type)

Overrides:

equals in class java.lang.Object

toString

public java.lang.String toString()

Overrides:

toString in class java.lang.Object

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method