text:
<?php

namespace AppBundle\Twig;

/**
 * CAUTION: this is an extremely advanced Twig extension. It's used to get the
 * source code of the controller and the template used to render the current
 * page. If you are starting with Symfony, don't look at this code and consider
 * studying instead the code of the src/AppBundle/Twig/AppExtension.php extension.
 *
 * @author Ryan Weaver <weaverryan@gmail.com>
 * @author Javier Eguiluz <javier.eguiluz@gmail.com>
 */
class SourceCodeExtension extends \Twig_Extension
{
    /**
     * @var \Twig_LoaderInterface
     */
    protected $loader;
    /**
     * @var
     */
    protected $controller;
    /**
     * @var
     */
    protected $template;
    /**
     * @var
     */
    protected $kernelRootDir;

    /**
     * @param \Twig_LoaderInterface $loader
     * @param $kernelRootDir
     */
    public function __construct(\Twig_LoaderInterface $loader, $kernelRootDir)
    {
        $this->kernelRootDir = $kernelRootDir;
        $this->loader = $loader;
    }

    /**
     * @param $controller
     */
    public function setController($controller)
    {
        $this->controller = $controller;
    }

    /**
     * @return array
     */
    public function getFunctions()
    {
        return array(
            new \Twig_SimpleFunction(
                'show_source_code',
                array($this, 'showSourceCode'),
                array('is_safe' => array('html'),
                    'needs_environment' => true)
            ),
        );
    }

    /**
     * @param \Twig_Environment $twig
     * @param $template
     * @return string
     */
    public function showSourceCode(\Twig_Environment $twig, $template)
    {
        $this->template = $template;

        return $twig->render('default/_source_code.html.twig', array(
            'controller' => $this->getController(),
            'template'   => $this->getTemplate(),
        ));
    }

    /**
     * @return array|void
     */
    private function getController()
    {
        // this happens for example for exceptions (404 errors, etc.)
        if (null === $this->controller) {
            return;
        }

        $className = get_class($this->controller[0]);
        $class = new \ReflectionClass($className);
        $method = $class->getMethod($this->controller[1]);

        $classCode = file($class->getFilename());
        $methodCode = array_slice(
            $classCode,
            $method->getStartline() - 1,
            $method->getEndLine() - $method->getStartline() + 1
        );
        $controllerCode = '    '.$method->getDocComment()."\n".implode('', $methodCode);

        return array(
            'file_path' => $class->getFilename(),
            'starting_line' => $method->getStartline(),
            'source_code' => $this->unindentCode($controllerCode)
        );
    }

    /**
     * @return array
     */
    private function getTemplate()
    {
        $templateName = $this->template->getTemplateName();

        return array(
            'file_path' => $this->kernelRootDir.'/Resources/views/'.$templateName,
            'starting_line' => 1,
            'source_code' => $this->loader->getSource($templateName),
        );
    }

    /**
     * Utility method that "unindents" the given $code when all its lines start
     * with a tabulation of four white spaces.
     *
     * @param  string $code
     * @return string
     */
    private function unindentCode($code)
    {
        $formattedCode = '';
        $codeLines = explode("\n", $code);

        $indentedLines = array_filter($codeLines, function ($lineOfCode) {
            return '' === $lineOfCode || '    ' === substr($lineOfCode, 0, 4);
        });

        if (count($indentedLines) === count($codeLines)) {
            $formattedCode = array_map(function ($lineOfCode) {
                return substr($lineOfCode, 4);
            }, $codeLines);
            $formattedCode = implode("\n", $formattedCode);
        } else {
            $formattedCode = $code;
        }

        return $formattedCode;
    }

    // the name of the Twig extension must be unique in the application
    /**
     * @return string
     */
    public function getName()
    {
        return 'app.source_code_extension';
    }
}


text:
#pragma once
#include "stored_data.h"

namespace dance {

class Interval;
class Motion;
class Plan;
class Step;
class Straight;
class Tile;

#define EPSILON 0.01

const int	NOT_AN_ANGLE = 1000000;

class FlowState {
public:
	int	turnState;			// 0 = neutral, < 0 = turning right, > 0 = turning left (magnitude >= 8 is possibly bad)
							// each 1/4 turn with radius = 1 (1/2 position), such as an arm turn increases magnitude by 2
	double	lastMotion;		// angle of last motion. (NOT_AN_ANGLE if dancer was not moving)

	FlowState() {
		turnState = 0;
		lastMotion = NOT_AN_ANGLE;
	}

	void idle(int dancerIndex, beats duration, Stage* stage);

	void turn(int dancerIndex, double angle, beats duration, double radius, Stage* stage);

	void straight(int dancerIndex, double angle, beats duration, Stage* stage);		// motion angle
};

const int EXCESSIVE_TURN = 12;		// 12 = 6 quarter turns in a row
const int OVER_TURN = 8;			// 8 = 4 quarter turns in a row, these should be followed by reverse turns to 'unwind'

class MotionSet {
public:
	MotionSet(bool startTogether);

	~MotionSet();

	bool validate(const Group* start, const Group* final) const;

	void checkFlow(FlowState* flowState, Stage* stage) const;

	Motion* lastCurve(int index, bool lastMotionOnly) const;

	void remember(MotionSet* ms);

	void remember(int dancerIndex, Motion* m);

	void replace(int dancerIndex, Motion* m);

	void also(int dancerIndex, Straight* m);

	void setRotation(int rotation) { _rotation = rotation; }

	beats duration() const;

	Motion* motion(int i) const;

	void print() const { printCommon(0); }

	int dancerCount() const { return _motions.size(); }

	bool startTogether() const { return _startTogether; }

	MotionSet* enclosing() const { return _enclosing; }

	bool remembered() const { return _remembered; }

protected:
	void printCommon(int indent) const;

	MotionSet* _enclosing;

	const vector<Straight*>& alsos() const { return _alsos; }

	vector<Motion*>& motions() { return _motions; }

private:
	vector<Straight*> _alsos;
	vector<Motion*> _motions;
	bool _startTogether;
	bool _remembered;
	int _rotation;
};
/*
 *	Interval
 *
 *	This identifies a set of motions by dancers.  The motions of each dancer is independent
 *	of the others and as soon as a given motion is completed, that dancer starts its next
 *	motion without waiting.
 *
 *	Each interval, however, must be finished before the next interval can start.
 */
class Interval : public MotionSet {
public:
	Interval(MotionSet* enclosing, bool startTogether) : MotionSet(startTogether) {
		_enclosing = enclosing;
	}

	~Interval() {
	}

	void print(int indent) const;

	void currentDancers(const Group* dancers) {
		_currentDancers = dancers;
	}

	void arc(const Dancer* dancer, Point center, double radius, double motionAngle, int noseQuarterTurns, beats duration, Context* context);

	void constructArc(const Dancer* dancer, const Point& center, const Point& start, const Point& end, double radius, double motionAngle, double startNose, double noseMotion, beats duration, Context* context);

	void forwardVeer(const Dancer* dancer, Point delta, float startYAdjust, double motionAngleAdjust, int rightQuarterTurns, beats duration, Context* context);

	void ringToSet(const Dancer* dancer, const Group* set, const Dancer* setDancer, beats duration, Context* context);

	void setToRing(const Dancer* dancer, const Group* ring, const Dancer* ringDancer, int ringX, int ringY, beats duration, Context* context);

	void trim(unsigned mask);

	void fillGaps(const Group* dancers, Context* context);

	void fillGaps(Motion* m, const Dancer* d, beats duration, Context* context);

	void also(const Dancer* dancer, int deltaX, int deltaY, Context* context);

	void displace(const Dancer* dancer, float startX, float startY, float deltaX, float deltaY, int rightQuarterTurns, double motionAngleAdjust, beats duration, Context* context);

	Motion* pause(Motion* previous, const Dancer* dancer, beats duration, Context* context);

	void perform(int dancerIndex, Motion* m);
	/*
	 *	lastCurve
	 *
	 *	lastMotionOnly:
	 *		false		Skip any straight motions to look for the last Curve available
	 *		true		Use the last motion of the dancer, Straight or Curve.
	 */
	Motion* lastCurve(const Dancer* dancer, bool lastMotionOnly) const;

	void matchTo(const Dancer* dancer, Context* context);

private:
	const Group* _currentDancers;
};

class Point {
public:
	Point(float x, float y) {
		this->x = x;
		this->y = y;
	}

	Point() {
		x = 0;
		y = 0;
	}

	double distance() const;

	bool operator == (const Point& p2) const {
		if (x != p2.x)
			return false;
		return y == p2.y;
	}

	float		x;
	float		y;
};

class Motion {
public:
	void prepend(Motion* prev) {
		_previous = prev;
	}

	void combine(Motion* also) {
		_also = also;
	}

	void scheduleAfter(beats startAt);

	double effectiveNoseMotion() const;

	double effectiveStartNose() const;

	double effectiveStartX() const;

	double effectiveStartY() const;

	double cumulativeNoseMotion() const;

	double cumulativeStartNose() const;

	double cumulativeStartX() const;

	double cumulativeStartY() const;

	double cumulativeEndX() const;

	double cumulativeEndY() const;

	double cumulativeEndNose() const;

	double cumulativeRadius() const;

	bool validate(float* fx, float* fy, double* fNoseAngle) const;

	void checkFlow(int dancerIndex, FlowState& flowState, Stage* stage, Motion* top) const;

	virtual void checkThis(int dancerIndex, FlowState& flowState, Stage* stage, Motion* top) const = 0;

	virtual void accumulateAlsoMotion(int at, double* deltaX, double* deltaY) const = 0;

	virtual void location(double fraction, double* x, double* y) const = 0;

	virtual void print(int indent) const = 0;

	Motion* split(const Group* pair, Point start, Facing* facing, int forward, int lateral, Context* context) const;

	virtual Motion* splitThis(const Group* pair, Point start, int forward, int lateral, Context* context) const = 0;

	Motion* fillGaps(const Group* startingDancers, const Dancer* d, beats duration);

	void finalizeAlso();

	void convertAlsoToStraight();

	const Point& start() const { return _start; }

	const Point& end() const { return _end; }

	double startNose() const { return _startNose; }

	double noseMotion() const { return _noseMotion; }

	void setDuration(beats duration) { _duration = duration; }

	beats endAt() const { return _startAt + _duration; }

	beats startAt() const { return _startAt; }

	beats duration() const { return _duration; }

	Motion* previous() const { return _previous; }

	Motion* also() const { return _also; }

protected:
	Motion(Point start, Point end, double startNose, double noseMotion, beats duration) {
		_start = start;
		_end = end;
		_startNose = startNose;
		_noseMotion = noseMotion;
		_duration = duration;
		_startAt = 0;
		_previous = null;
		_also = null;
	}

	Motion(int deltaX, int deltaY, Motion* also, beats duration) {
		_end.x = deltaX;
		_end.y = deltaY;
		_duration = duration;
		_noseMotion = 0;
		_startNose = 0;
		_startAt = 0;
		_previous = null;
		_also = also;
	}

	void printCommon(int indent) const;

private:
	Motion() {}

	Point			_start;			// starting dancer position
	Point			_end;			// Ending dancer position
	double			_startNose;		// starting nose angle (in radians)
	double			_noseMotion;	// direction and magnitude (in radians) of motion
	beats			_startAt;		// # of beats after start of the stage to start this motion
	beats			_duration;		// time needed for motion
	Motion*			_previous;		// previous motion in time along this chain of motions.
	Motion*			_also;			// Motions to be combined with this one.
};

class Straight : public Motion {
	friend Stage;
public:
	virtual void location(double fraction, double* x, double* y) const;

	virtual Motion* splitThis(const Group* pair, Point start, int forward, int lateral, Context* context) const;

	virtual void checkThis(int dancerIndex, FlowState& flowState, Stage* stage, Motion* top) const;

	virtual void accumulateAlsoMotion(int at, double* deltaX, double* deltaY) const;

	virtual void print(int indent) const;

private:
	Straight(Point start, Point end, double startNose, double noseMotion, beats duration)
		: Motion(start, end, startNose, noseMotion, duration) {
	}

};

class Curve : public Motion {
	friend Stage;
public:
	virtual void location(double fraction, double* x, double* y) const;

	virtual Motion* splitThis(const Group* pair, Point start, int forward, int lateral, Context* context) const;

	virtual void checkThis(int dancerIndex, FlowState& flowState, Stage* stage, Motion* top) const;

	virtual void accumulateAlsoMotion(int at, double* deltaX, double* deltaY) const;

	virtual void print(int indent) const;

	double radius() const { return _radius; }

private:
	Curve(Point center, double motionAngle, double radius, Point start, Point end, double startNose, double noseMotion, beats duration)
		: Motion(start, end, startNose, noseMotion, duration) {
		_center = center;
		_motionAngle = motionAngle;
		_radius = radius;
	}
	Point			_center;		// center of any arcing motion
	double			_motionAngle;	// direction and magnitude (in radians) of motion
	double			_radius;		// radius of ending dancer position
};

}  // namespace dance

redpajama_set_name: RedPajamaGithub


text:
@interface CCMWindowController : NSObject <NSToolbarDelegate>
{
	NSDictionary	*toolbarDefinition;
}

- (NSToolbar *)createToolbarWithName:(NSString *)name;

@end


text:
using System.Collections.Generic;
using Orchard;

namespace RadioSystems.React.Services {
    public interface IReactHarvester : IDependency {
        IEnumerable<string> ReactFolderPaths();
        IEnumerable<string> HarvestReactEnabledModules();
        IEnumerable<string> HarvestReducers(string path);
        IEnumerable<string> HarvestRoutes(string path);
        IEnumerable<string> HarvestModals(string path);
    }
}


text:
package com.app.comic.utils;

import android.Manifest;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.Point;
import android.graphics.drawable.ShapeDrawable;
import android.graphics.drawable.shapes.RoundRectShape;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.CalendarContract;
import android.provider.CalendarContract.Events;
import android.provider.Settings.Secure;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.util.Base64;
import android.util.DisplayMetrics;
import android.util.TypedValue;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.TextView;
import android.widget.Toast;

import com.app.comic.R;

import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Random;

public class Utils {

    public static final int MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE = 1;
    public static final int MY_PERMISSIONS_REQUEST_CAMERA = 2;

    @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
    public static boolean checkPermissionGallery(final Context context)
    {
        int currentAPIVersion = Build.VERSION.SDK_INT;
        if(currentAPIVersion>=android.os.Build.VERSION_CODES.M)
        {
            if (ContextCompat.checkSelfPermission(context, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                if (ActivityCompat.shouldShowRequestPermissionRationale((Activity) context, Manifest.permission.READ_EXTERNAL_STORAGE)) {
                    AlertDialog.Builder alertBuilder = new AlertDialog.Builder(context);
                    alertBuilder.setCancelable(true);
                    alertBuilder.setTitle("Permission necessary");
                    alertBuilder.setMessage("External storage permission is necessary");
                    alertBuilder.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
                        @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
                        public void onClick(DialogInterface dialog, int which) {
                            ActivityCompat.requestPermissions((Activity) context, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE);
                        }
                    });
                    AlertDialog alert = alertBuilder.create();
                    alert.show();
                } else {
                    ActivityCompat.requestPermissions((Activity) context, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE);
                }
                return false;
            } else {
                return true;
            }
        } else {
            return true;
        }
    }

    @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
    public static boolean checkPermissionCamera(final Context context)
    {
        int currentAPIVersion = Build.VERSION.SDK_INT;
        if(currentAPIVersion>=android.os.Build.VERSION_CODES.M)
        {
            if (ContextCompat.checkSelfPermission(context, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
                if (ActivityCompat.shouldShowRequestPermissionRationale((Activity) context, Manifest.permission.CAMERA)) {
                    AlertDialog.Builder alertBuilder = new AlertDialog.Builder(context);
                    alertBuilder.setCancelable(true);
                    alertBuilder.setTitle("Permission necessary");
                    alertBuilder.setMessage("External storage permission is necessary");
                    alertBuilder.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
                        @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
                        public void onClick(DialogInterface dialog, int which) {
                            ActivityCompat.requestPermissions((Activity) context, new String[]{Manifest.permission.CAMERA}, MY_PERMISSIONS_REQUEST_CAMERA);
                        }
                    });
                    AlertDialog alert = alertBuilder.create();
                    alert.show();
                } else {
                    ActivityCompat.requestPermissions((Activity) context, new String[]{Manifest.permission.CAMERA}, MY_PERMISSIONS_REQUEST_CAMERA);
                }
                return false;
            } else {
                return true;
            }
        } else {
            return true;
        }
    }

    public static void launchBrowser(Context context, String url) {
        try {
            Uri uriUrl = Uri.parse(url);
            Intent launchBrowser = new Intent(Intent.ACTION_VIEW, uriUrl);
            context.startActivity(launchBrowser);
        } catch (NullPointerException e) {
            e.printStackTrace();
        } catch (ActivityNotFoundException e) {
            e.printStackTrace();
        }
    }

    public static void launchNavigator(Context context, String url) {
        try {
            Uri uriUrl = Uri.parse(url);
            Intent navigator = new Intent(Intent.ACTION_VIEW, uriUrl);
            context.startActivity(navigator);

        } catch (NullPointerException e) {
            e.printStackTrace();
        } catch (ActivityNotFoundException e) {
            e.printStackTrace();
        }
    }

    public static String getDeviceType(Activity activity) {
        String deviceType = null;
        if ((activity.getResources().getConfiguration().screenLayout &
                Configuration.SCREENLAYOUT_SIZE_MASK) >= Configuration.SCREENLAYOUT_SIZE_LARGE) {
            deviceType = "1";
        } else {
            deviceType = "2";
        }

        return deviceType;

    }

    public static void launchNavigator(Context context, double lat, double lng) {
        try {
            Intent navIntent = new Intent(Intent.ACTION_VIEW);
            navIntent.setData(Uri.parse(String.format("geo: %s,%s", lat, lng)));
            context.startActivity(navIntent);
        } catch (NullPointerException e) {
            e.printStackTrace();
        } catch (ActivityNotFoundException e) {
            e.printStackTrace();
        }
    }

    public static String bitmapToBase64(Bitmap b) {
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        b.compress(Bitmap.CompressFormat.PNG, 100, byteArrayOutputStream);
        byte[] byteArray = byteArrayOutputStream.toByteArray();
        return Base64.encodeToString(byteArray, Base64.DEFAULT);
    }

    public static void makeCall(Context context, String phone) {
        try {
            Intent callIntent = new Intent(Intent.ACTION_CALL);
            callIntent.setData(Uri.parse("tel: " + phone));
            context.startActivity(callIntent);
        } catch (NullPointerException e) {
            e.printStackTrace();
        } catch (ActivityNotFoundException e) {
            e.printStackTrace();
        }
    }

    public static void addCalendar(Context context, String title, String location, String description, Date startDate, Date endDate) {
        try {
            Intent calIntent = new Intent(Intent.ACTION_EDIT);
            calIntent.setType("vnd.android.cursor.item/event");
            calIntent.putExtra(Events.TITLE, title);
            calIntent.putExtra(Events.EVENT_LOCATION, location);
            calIntent.putExtra(Events.DESCRIPTION, description);

            calIntent.putExtra(CalendarContract.EXTRA_EVENT_ALL_DAY, false);
            calIntent.putExtra(CalendarContract.EXTRA_EVENT_BEGIN_TIME, startDate.getTime());
            calIntent.putExtra(CalendarContract.EXTRA_EVENT_END_TIME, endDate.getTime());
            context.startActivity(calIntent);
        } catch (NullPointerException e) {
            e.printStackTrace();
        } catch (ActivityNotFoundException e) {
            e.printStackTrace();
        }
    }

    public static void alert(Context context, String title, String message, String yesText, String noText, DialogInterface.OnClickListener dialogClickListener) {
        yesText = (yesText == null || yesText.isEmpty()) ? "Yes" : yesText;
        noText = (noText == null || noText.isEmpty()) ? "No" : noText;

        AlertDialog.Builder builder = new AlertDialog.Builder(context);
        builder.setTitle(title);
        builder.setMessage(message);
        builder.setPositiveButton(yesText, dialogClickListener);
        builder.setNegativeButton(noText, dialogClickListener);
        builder.show();
    }

    /* Get width number by percentage of this device screen */
    public static int getScreenWidthByPercent(Activity activity, int percent) {
        ScreenDensity dpi = new ScreenDensity(activity);
        return (percent / 100) * dpi.getWidth();
    }

    /* Get height number by percentage of this device screen */
    public static int getScreenHeightByPercent(Activity activity, int percent) {
        ScreenDensity dpi = new ScreenDensity(activity);
        return (percent / 100) * dpi.getHeight();
    }

    /* Checks if external storage is available for read and write */
    public static boolean isExternalStorageWritable() {
        String state = Environment.getExternalStorageState();
        return (Environment.MEDIA_MOUNTED.equals(state)) ? true : false;
    }

    /* Checks if external storage is available to at least read */
    public static boolean isExternalStorageReadable() {
        String state = Environment.getExternalStorageState();
        return (Environment.MEDIA_MOUNTED.equals(state) || Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) ? true : false;
    }

    public static String getAndroidId(Activity activity) {
        try {
            return Secure.getString(activity.getContentResolver(), Secure.ANDROID_ID);

        } catch (NullPointerException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void getScreenDpi(Context context) {
        int screenSize = context.getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK;
        String toastMsg = "";
        switch (screenSize) {
            case Configuration.SCREENLAYOUT_SIZE_LARGE:
                toastMsg = "Large screen ";
                break;
            case Configuration.SCREENLAYOUT_SIZE_NORMAL:
                toastMsg = "Normal screen ";
                break;
            case Configuration.SCREENLAYOUT_SIZE_SMALL:
                toastMsg = "Small screen ";
                break;
            default:
                toastMsg = "Screen size is neither large, normal or small";
        }

        switch (context.getResources().getDisplayMetrics().densityDpi) {
            case DisplayMetrics.DENSITY_LOW:
                // handle your code here for ldpi
                toastMsg += "ldpi";
                break;
            case DisplayMetrics.DENSITY_MEDIUM:
                // handle your code here for mdpi
                toastMsg += "mdpi";
                break;
            case DisplayMetrics.DENSITY_HIGH:
                // handle your code here for hdpi
                toastMsg += "hdpi";
                break;
            case DisplayMetrics.DENSITY_XHIGH:
                // handle your code here for xhdpi
                toastMsg += "xhdpi";
                break;
        }

        Toast.makeText(context, toastMsg, Toast.LENGTH_LONG).show();
    }

    public static void log(String text) {
        File logFile = new File("sdcard/log.txt");
        if (!logFile.exists()) {
            try {
                logFile.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        try {
            // BufferedWriter for performance, true to set append to file flag
            BufferedWriter buf = new BufferedWriter(new FileWriter(logFile, true));
            buf.append(text);
            buf.newLine();
            buf.newLine();
            buf.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void hideKeyboard(Activity activity, View v) {
        InputMethodManager imm = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
    }

    public static void toastNotification(Activity activity, String msg) {
        Context context = activity;
        CharSequence text = msg;
        int duration = Toast.LENGTH_SHORT;

        Toast toast1 = Toast.makeText(context, text, duration);
        toast1.show();

        /*final Toast toast2 = Toast.makeText(context, text, duration);
        toast2.show();

        Handler toast_handler = new Handler();
        toast_handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                toast2.show();
            }
        }, duration - 50);
        */

    }

    public static void toastNotificationLong(Activity activity, String msg) {
        Context context = activity;
        CharSequence text = msg;
        int duration = Toast.LENGTH_LONG;

        Toast toast1 = Toast.makeText(context, text, duration);
        toast1.show();

        /*final Toast toast2 = Toast.makeText(context, text, duration);
        toast2.show();

        Handler toast_handler = new Handler();
        toast_handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                toast2.show();
            }
        }, duration - 50);
        */

    }

    public static String getRandomImageUrl() {
        Random r = new Random();
        String[] images = {"http://icons.iconarchive.com/icons/webalys/kameleon.pics/128/Alien-icon.png",
                "http://icons.iconarchive.com/icons/webalys/kameleon.pics/128/Analytics-icon.png",
                "http://icons.iconarchive.com/icons/webalys/kameleon.pics/128/Apartment-icon.png",
                "http://icons.iconarchive.com/icons/webalys/kameleon.pics/128/Battery-Charging-icon.png",
                "http://icons.iconarchive.com/icons/webalys/kameleon.pics/128/Batman-icon.png",
                "http://icons.iconarchive.com/icons/webalys/kameleon.pics/128/Bag-Present-icon.png",
                "http://icons.iconarchive.com/icons/webalys/kameleon.pics/128/Boss-2-icon.png",
                "http://icons.iconarchive.com/icons/webalys/kameleon.pics/128/Burglar-icon.png",
                "http://icons.iconarchive.com/icons/webalys/kameleon.pics/128/Camera-Front-icon.png",};
        return images[r.nextInt(images.length)];
    }

    public static ShapeDrawable getRoundedButton(Activity activity, float radius, int color) {
        float px = convertDpInt(activity, radius);
        float[] outerR = new float[]{px, px, px, px, px, px, px, px};
        RoundRectShape rr = new RoundRectShape(outerR, null, null);
        ShapeDrawable sd = new ShapeDrawable(rr);
        sd.getPaint().setColor(color);
        return sd;
    }

    public static int convertDpInt(Activity activity, float value) {
        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, value, activity.getResources().getDisplayMetrics());
    }

    public static String getVersion(Activity activity) {
        String version = "";
        try {
            PackageInfo packageInfo = activity.getPackageManager().getPackageInfo(activity.getPackageName(), 0);
            version = String.format("v%s r%s", packageInfo.versionName, packageInfo.versionCode);
        } catch (NameNotFoundException e) {
            e.printStackTrace();
        }
        return version;
    }

    public static String addressFormater(String street1, String street2, String street3) {
        String address, s1 = null, s2 = null, s3 = null;
        String returnAddress;

        if (!street1.equals("")) {
            s1 = street1;
        }
        if (!street2.equals("")) {
            s2 = "\n" + street2;
        }
        if (!street3.equals("")) {
            s3 = "\n" + street3;
        }
        address = s1 + s2 + s3;
        returnAddress = address.replace("null", "");

        return returnAddress;
    }

    public static String replaceAMP(String code) {
        String test = code.replace("&", "&");
        return test;
    }

    public static boolean isNetworkAvailable(Activity activity) {
        ConnectivityManager connectivityManager = (ConnectivityManager) activity.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
        return activeNetworkInfo != null && activeNetworkInfo.isConnected();
    }

    public static int getNDate() {
        Calendar calendar = Calendar.getInstance();
        int year = calendar.get(Calendar.YEAR);

        return year;
    }

    public static String trim(String string) {
        if (string.contains("anyType{}")) {
            return string.replace("anyType{}", "");
        }

        return string;
    }

    public static class ScreenDensity {
        private int width = 0;
        private int height = 0;

        @SuppressWarnings("deprecation")
        public ScreenDensity(Activity activity) {
            Display display = activity.getWindowManager().getDefaultDisplay();
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
                Point size = new Point();
                display.getSize(size);
                width = size.x;
                height = size.y;
            } else {
                width = display.getWidth(); // deprecated
                height = display.getHeight(); // deprecated
            }
        }

        public int getWidth() {
            return width;
        }

        public int getHeight() {
            return height;
        }
    }

    public static int convertDPToPixel(Context context, int dp) {
        final float scale = context.getResources().getDisplayMetrics().density;
        int px = (int) (dp * scale + 0.5f);

        return px;
    }

    public static String formatDateAndTime(String DateAndTime) {

        String newFormat = null;
        SimpleDateFormat inputDF = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSz");
        SimpleDateFormat formattedDate = new SimpleDateFormat("yyyy/MM/dd HH:mm");

        try {
            newFormat = formattedDate.format(inputDF.parse(DateAndTime));
        } catch (ParseException e) {
            e.printStackTrace();
        }

        return newFormat;
    }

    public static String formatDate(String Date) {

        String newFormatDate = null;
        SimpleDateFormat inputDF = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSz");
        SimpleDateFormat formattedDate = new SimpleDateFormat("dd/MM/yyyy");

        try {
            newFormatDate = formattedDate.format(inputDF.parse(Date));
        } catch (ParseException e) {
            e.printStackTrace();
        }

        return newFormatDate;
    }
}


text:
<?php
require_once('_header.inc.php');

// load all file servers
$sQL = "SELECT id, serverLabel FROM file_server ORDER BY serverLabel";
$serverDetails = $db->getRows($sQL);

// load all users
$sQL = "SELECT id, username AS selectValue FROM users ORDER BY username";
$userDetails = $db->getRows($sQL);

// do we need to filter by user
$userFilter = false;
if(isset($_REQUEST['user']))
{
    $userFilter = (int)$_REQUEST['user'];

    // load user details
    $userObj = UserPeer::loadUserById($userFilter);
}
?>

        <?php echo t("files_filter_results", "Filter Results:"); ?>

        <input id="files_search" name="files_search" class="fileSearch" value="" type="text" onKeyUp="mfScripts.filesTable.updateFilteredResults();"/>

        <?php echo t("files_filter_user", "By User"); ?>:

        <select id="file_search_user" name="file_search_user" onChange="mfScripts.filesTable.updateFilteredResults();">
            <option value="">- all -</option>
            <?php
            if(COUNT($userDetails))
            {
                foreach($userDetails AS $userDetail)
                {
                    echo '<option value="'.$userDetail['id'].'"';
                    if(($userFilter) && ($userFilter == $userDetail['id']))
                    {
                        echo ' SELECTED';
                    }
                    echo '>'.$userDetail['selectValue'].'</option>';
                }
            }
            ?>
        </select>

        <?php echo t("files_filter_server", "By File Server"); ?>:

        <select id="file_search_server" name="file_search_server" onChange="mfScripts.filesTable.updateFilteredResults();">
            <option value="">- all -</option>
            <?php
            if(COUNT($serverDetails))
            {
                foreach($serverDetails AS $serverDetail)
                {
                    echo '<option value="'.$serverDetail['id'].'">'.$serverDetail['serverLabel'].'</option>';
                }
            }
            ?>
        </select>

        <?php echo t("files_filter_removed", "Show Removed"); ?>:

        <input id="file_search_disabled" name="file_search_disabled" value="1" type="checkbox" onChange="mfScripts.filesTable.updateFilteredResults();"/>

<?php echo t("export_files_as_csv", "Export File Data"); ?>

<?php
require_once('_footer.inc.php');
?>


text:
package ch.sbi.scraper.mapper;

import ch.sbi.scraper.datatype.marshalling.Thread;
import ch.sbi.scraper.factory.MarshallerFactory;
import ch.sbi.scraper.library.utility.SourceBuilder;

import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import javax.xml.transform.Source;
import java.util.stream.IntStream;
import java.util.stream.Stream;

/**
 * Class for fetching and mapping Thread XML files to their runtime representation.
 */
public class ThreadMapper {
    private final SourceBuilder sourceBuilder;

    public ThreadMapper(SourceBuilder sourceBuilder) {
        this.sourceBuilder = sourceBuilder;
    }

    /**
     * Unmarshalls the first page of the thread with the given id.
     *
     * @param id Thread id
     * @return Unmarshalled thread, or a dummy thread object containing no information.
     */
    public Thread getThread(long id) {
        return getThread(id, 1);
    }

    /**
     * Unmarshalls the given page of the thread with the given id.
     *
     * @param id Thread id
     * @param page Thread page
     * @return Unmarshalled page, or a dummy thread object containing no information.
     */
    public Thread getThread(long id, int page) {
        try {
            Source threadSource = sourceBuilder.getThreadSource(id, page);
            Unmarshaller unmarshaller = new MarshallerFactory(Thread.class).getUnmarshaller();
            return unmarshaller.unmarshal(threadSource, Thread.class).getValue();
        } catch (JAXBException e) {
            // object creation failed, return a dummy object
            // TODO: This should also use Optional
            return new Thread();
        }
    }

    /**
     * Returns a Stream of thread objects, each representing a page of the given Thread.
     *
     * @param id Thread for which to stream all pages
     * @return Stream with all pages of the given thread
     */
    public Stream<Thread> getPages(long id) {
        Thread thread = getThread(id);
        return IntStream
                .rangeClosed(1, thread.getNumberOfPages().getValue().intValue())
                .mapToObj(i -> getThread(id, i))
                .filter(t -> Integer.valueOf(t.getPosts().getCount()) > 0);
    }
}


text:
namespace nbody {

  class System {
    size_t _nBodies;
    Body *_body;
    float _softFactor = 1e-9f;
    float _dampingFactor = 1.0f;
    System() = delete;
    System( const System &sys ) = delete;
    System& operator=( const System &sys ) = delete;
  public:
    System( size_t N ) : _nBodies{N}, _body{ new Body[N] } { initRandomState(); }
    System( std::istream &input ) : _nBodies{}, _body{nullptr} { readState( input ); }
    System( std::string filename ) : _nBodies{}, _body{nullptr} { readState( filename ); }
    ~System() { delete [] _body; }
    void interactBodies( size_t i, size_t j, float softFactor, Vector3f &acc ) const;
    void computeGravitation();
    void integrateSystem( float dt );
    void readState( std::istream &input );
    void readState( std::string filename );
    void writeState( std::ostream &output ) const;
    void writeState( std::string filename ) const;
    void initRandomState();
    void update( float dt );
    void setSoftening( float soft ) { _softFactor = soft; }
    void setDamping( float damp ) { _dampingFactor = damp; }
  };

} // namespace nbody

#endif // _NBODY_SYSTEM_H


text:
from __future__ import print_function

import setuptools

setuptools.setup(
    name="apigateway-helpers",
    version="0.1",
    author="Benn Linger",
    author_email="benn@linger.com",
    url="https://github.com/moduspwnens",
    description="Helper methods for use with API Gateway by Lambda.",
    packages=setuptools.find_packages()
)


text:
module Gitlab
  module Metrics
    module Dashboard
      class ServiceSelector
        SERVICES = ::Metrics::Dashboard

        class << self
          include Gitlab::Utils::StrongMemoize

          # Returns a class which inherits from the BaseService
          # class that can be used to obtain a dashboard.
          # @return [Gitlab::Metrics::Dashboard::Services::BaseService]
          def call(params)
            return SERVICES::CustomMetricEmbedService if custom_metric_embed?(params)
            return SERVICES::DynamicEmbedService if dynamic_embed?(params)
            return SERVICES::DefaultEmbedService if params[:embedded]
            return SERVICES::SystemDashboardService if system_dashboard?(params[:dashboard_path])
            return SERVICES::ProjectDashboardService if params[:dashboard_path]

            default_service
          end

          private

          def default_service
            SERVICES::SystemDashboardService
          end

          def system_dashboard?(filepath)
            SERVICES::SystemDashboardService.system_dashboard?(filepath)
          end

          def custom_metric_embed?(params)
            SERVICES::CustomMetricEmbedService.valid_params?(params)
          end

          def dynamic_embed?(params)
            SERVICES::DynamicEmbedService.valid_params?(params)
          end
        end
      end
    end
  end
end

Gitlab::Metrics::Dashboard::ServiceSelector.prepend_if_ee('EE::Gitlab::Metrics::Dashboard::ServiceSelector')


text:
package org.onosproject.net.driver;

import java.util.Optional;

import com.google.common.annotations.Beta;

/**
 * Abstraction of an entity capable of being projected as another entity.
 */
@Beta
public interface Projectable {

    /**
     * Returns the specified projection of this entity if such projection
     * is supported.
     *
     * @param projectionClass requested projection class
     * @param <B> type of behaviour
     * @return projection instance
     * @throws IllegalStateException if a driver cannot be found
     * @throws IllegalArgumentException if the projection is not supported
     */
    <B extends Behaviour> B as(Class<B> projectionClass);

    /**
     * Returns true if this entity is capable of being projected as the
     * specified class.
     *
     * @param projectionClass requested projection class
     * @param <B> type of behaviour
     * @return true if the requested projection is supported
     */
    <B extends Behaviour> boolean is(Class<B> projectionClass);

    /**
     * Returns the specified projection of this entity if such projection
     * is supported.
     *
     * @param projectionClass requested projection class
     * @param <B> type of behaviour
     * @return projection instance
     */
    default <B extends Behaviour> Optional<B> project(Class<B> projectionClass) {
        if (is(projectionClass)) {
            return Optional.of(as(projectionClass));
        } else {
            return Optional.empty();
        }
    }

}


text:
// Copyright 2013 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

package org.chromium.chrome.browser.layouts;

import android.content.Context;
import android.view.MotionEvent;

import androidx.annotation.VisibleForTesting;

/**
 * A class intended to process input events for non-android views.
 */
public abstract class EventFilter {
    protected final float mPxToDp;
    private boolean mSimulateIntercepting;

    private boolean mAutoOffset;
    protected float mCurrentTouchOffsetX;
    protected float mCurrentTouchOffsetY;

    /**
     * Creates a {@link EventFilter}.
     * @param context A {@link Context} instance.
     */
    public EventFilter(Context context) {
        this(context, true);
    }

    /**
     * Creates a {@link EventFilter}.
     * @param autoOffset Whether or not to automatically offset touch events.
     */
    public EventFilter(Context context, boolean autoOffset) {
        mPxToDp = 1.0f / context.getResources().getDisplayMetrics().density;
        mAutoOffset = autoOffset;
    }

    /**
     * @see android.view.ViewGroup#onInterceptTouchEvent(android.view.MotionEvent)
     * @param event             The {@link MotionEvent} that started the gesture to be evaluated.
     * @param isKeyboardShowing Whether the keyboard is currently showing.
     * @return                  Whether the filter is going to intercept events.
     */
    public final boolean onInterceptTouchEvent(MotionEvent event, boolean isKeyboardShowing) {
        MotionEvent sentEvent = event;
        if (mAutoOffset && (mCurrentTouchOffsetX != 0 || mCurrentTouchOffsetY != 0)) {
            sentEvent = MotionEvent.obtain(event);
            sentEvent.offsetLocation(mCurrentTouchOffsetX, mCurrentTouchOffsetY);
        }
        boolean consumed = onInterceptTouchEventInternal(sentEvent, isKeyboardShowing);
        if (sentEvent != event) sentEvent.recycle();
        return consumed;
    }

    /**
     * Sets the offset to apply to MotionEvents.
     *
     * @param offsetX How much to offset the X touch events in pixels.
     * @param offsetY How much to offset the Y touch events in pixels.
     */
    public void setCurrentMotionEventOffsets(float offsetX, float offsetY) {
        mCurrentTouchOffsetX = offsetX;
        mCurrentTouchOffsetY = offsetY;
    }

    /**
     * This function has a fairly uncommon behavior, if you change anything please checkout the
     * java-doc here:
     * @see android.view.ViewGroup#onInterceptTouchEvent(android.view.MotionEvent)
     * @param event             The {@link MotionEvent} that started the gesture to be evaluated.
     * @param isKeyboardShowing Whether the keyboard is currently showing.
     * @return                  Whether the filter is going to intercept events.
     */
    protected abstract boolean onInterceptTouchEventInternal(
            MotionEvent event, boolean isKeyboardShowing);

    /**
     * @see android.view.ViewGroup#onTouchEvent(android.view.MotionEvent)
     * @param event The {@link MotionEvent} that started the gesture to be evaluated.
     * @return      Whether the filter handled the event.
     */
    public final boolean onTouchEvent(MotionEvent event) {
        if (mAutoOffset) event.offsetLocation(mCurrentTouchOffsetX, mCurrentTouchOffsetY);
        return onTouchEventInternal(event);
    }

    /**
     * @see android.view.ViewGroup#onTouchEvent(android.view.MotionEvent)
     * @param event The {@link MotionEvent} that started the gesture to be evaluated.
     * @return      Whether the filter handled the event.
     */
    protected abstract boolean onTouchEventInternal(MotionEvent event);

    /**
     * Simulates an event for testing purpose. This will call onInterceptTouchEvent and
     * onTouchEvent appropriately.
     * @param event             The {@link MotionEvent} that started the gesture to be evaluated.
     * @param isKeyboardShowing Whether the keyboard is currently showing.
     * @return                  Whether the filter handled the event.
     */
    @VisibleForTesting
    public boolean simulateTouchEvent(MotionEvent event, boolean isKeyboardShowing) {
        if (event.getActionMasked() == MotionEvent.ACTION_DOWN || !mSimulateIntercepting) {
            mSimulateIntercepting = onInterceptTouchEvent(event, isKeyboardShowing);
        }
        return onTouchEvent(event);
    }
}


text:
from __future__ import absolute_import
from __future__ import print_function
import getopt
import sys

import happy.HappyNetworkList
from happy.Utils import *

if __name__ == "__main__":
    options = happy.HappyNetworkList.option()

    try:
        opts, args = getopt.getopt(sys.argv[1:], "hq",
                                   ["help", "quiet"])

    except getopt.GetoptError as err:
        print(happy.HappyNetworkList.HappyNetworkList.__doc__)
        print(hred(str(err)))
        sys.exit(hred("%s: Failed to parse arguments." % (__file__)))

    for o, a in opts:
        if o in ("-h", "--help"):
            print(happy.HappyNetworkList.HappyNetworkList.__doc__)
            sys.exit(0)

        elif o in ("-q", "--quiet"):
            options["quiet"] = True

        else:
            assert False, "unhandled option"

    cmd = happy.HappyNetworkList.HappyNetworkList(options)
    cmd.start()


text:
name: cljs.core/StringBufferWriter
see also:
---

## Summary

## Details

## Examples


text:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace kursach_l
{
    public partial class Form_main : Form
    {
        private Form_Title f;
        public Form_main(Form_Title f)
        {
            InitializeComponent();
            this.f = f;
        }

        private void Form_main_FormClosed(object sender, FormClosedEventArgs e)
        {
            Application.Exit();
        }

        private void M_exit_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        private void M_m1_Click(object sender, EventArgs e)
        {
            Form_1st_method f = new Form_1st_method();
            f.Show();
        }

        private void M_m2_Click(object sender, EventArgs e)
        {
            Form_2nd_method f = new Form_2nd_method();
            f.Show();
        }

        private void M_res_Click(object sender, EventArgs e)
        {
            Form_research f = new Form_research();
            f.Show();
        }

        private void M_m1_desc_Click(object sender, EventArgs e)
        {
            Form_1st_desc f = new Form_1st_desc();
            f.Show();
        }

        private void M_m1_fc_Click(object sender, EventArgs e)
        {
            Form_1st_fc f = new Form_1st_fc();
            f.Show();
        }

        private void M_m2_desc_Click(object sender, EventArgs e)
        {
            Form_2nd_desc f = new Form_2nd_desc();
            f.Show();
        }

        private void M_m2_fc_Click(object sender, EventArgs e)
        {
            Form_2nd_fc f = new Form_2nd_fc();
            f.Show();
        }

        private void M_ref_Click(object sender, EventArgs e)
        {
            Form_ref f = new Form_ref();
            f.Show();
        }

        private void M_about_Click(object sender, EventArgs e)
        {
            Form_about f = new Form_about();
            f.Show();
        }

        private void титульныйЛистToolStripMenuItem_Click(object sender, EventArgs e)
        {
            f.Visible = true;
            this.Dispose();
        }
    }
}


text:
package org.hibernate.metamodel.source.hbm;

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

import org.hibernate.EntityMode;
import org.hibernate.internal.jaxb.mapping.hbm.JaxbAnyElement;
import org.hibernate.internal.jaxb.mapping.hbm.JaxbComponentElement;
import org.hibernate.internal.jaxb.mapping.hbm.JaxbManyToManyElement;
import org.hibernate.internal.jaxb.mapping.hbm.JaxbManyToOneElement;
import org.hibernate.internal.jaxb.mapping.hbm.JaxbOneToManyElement;
import org.hibernate.internal.jaxb.mapping.hbm.JaxbOneToOneElement;
import org.hibernate.internal.jaxb.mapping.hbm.JaxbPropertyElement;
import org.hibernate.internal.jaxb.mapping.hbm.JaxbTuplizerElement;
import org.hibernate.internal.util.StringHelper;
import org.hibernate.internal.util.ValueHolder;
import org.hibernate.mapping.PropertyGeneration;
import org.hibernate.metamodel.source.LocalBindingContext;
import org.hibernate.metamodel.source.binder.AttributeSource;
import org.hibernate.metamodel.source.binder.AttributeSourceContainer;
import org.hibernate.metamodel.source.binder.ComponentAttributeSource;
import org.hibernate.metamodel.source.binder.ExplicitHibernateTypeSource;
import org.hibernate.metamodel.source.binder.MetaAttributeSource;
import org.hibernate.metamodel.source.binder.RelationalValueSource;
import org.hibernate.metamodel.source.binder.SingularAttributeNature;

/**
 * @author Steve Ebersole
 */
public class ComponentAttributeSourceImpl implements ComponentAttributeSource {
	private final JaxbComponentElement componentElement;
	private final AttributeSourceContainer parentContainer;

	private final ValueHolder<Class<?>> componentClassReference;
	private final String path;

	public ComponentAttributeSourceImpl(
			JaxbComponentElement componentElement,
			AttributeSourceContainer parentContainer,
			LocalBindingContext bindingContext) {
		this.componentElement = componentElement;
		this.parentContainer = parentContainer;

		this.componentClassReference = bindingContext.makeClassReference(
				bindingContext.qualifyClassName( componentElement.getClazz() )
		);
		this.path = parentContainer.getPath() + '.' + componentElement.getName();
	}

	@Override
	public String getClassName() {
		return componentElement.getClazz();
	}

	@Override
	public ValueHolder<Class<?>> getClassReference() {
		return componentClassReference;
	}

	@Override
	public String getPath() {
		return path;
	}

	@Override
	public LocalBindingContext getLocalBindingContext() {
		return parentContainer.getLocalBindingContext();
	}

	@Override
	public String getParentReferenceAttributeName() {
		return componentElement.getParent() == null ? null : componentElement.getParent().getName();
	}

	@Override
	public String getExplicitTuplizerClassName() {
		if ( componentElement.getTuplizer() == null ) {
			return null;
		}
		final EntityMode entityMode = StringHelper.isEmpty( componentElement.getClazz() ) ? EntityMode.MAP : EntityMode.POJO;
		for ( JaxbTuplizerElement tuplizerElement : componentElement.getTuplizer() ) {
			if ( entityMode == EntityMode.parse( tuplizerElement.getEntityMode() ) ) {
				return tuplizerElement.getClazz();
			}
		}
		return null;
	}

	@Override
	public Iterable<AttributeSource> attributeSources() {
		List<AttributeSource> attributeSources = new ArrayList<AttributeSource>();
		for ( Object attributeElement : componentElement.getPropertyOrManyToOneOrOneToOne() ) {
			if ( JaxbPropertyElement.class.isInstance( attributeElement ) ) {
				attributeSources.add(
						new PropertyAttributeSourceImpl(
								JaxbPropertyElement.class.cast( attributeElement ),
								getLocalBindingContext()
						)
				);
			}
			else if ( JaxbComponentElement.class.isInstance( attributeElement ) ) {
				attributeSources.add(
						new ComponentAttributeSourceImpl(
								(JaxbComponentElement) attributeElement,
								this,
								getLocalBindingContext()
						)
				);
			}
			else if ( JaxbManyToOneElement.class.isInstance( attributeElement ) ) {
				attributeSources.add(
						new ManyToOneAttributeSourceImpl(
								JaxbManyToOneElement.class.cast( attributeElement ),
								getLocalBindingContext()
						)
				);
			}
			else if ( JaxbOneToOneElement.class.isInstance( attributeElement ) ) {
				// todo : implement
			}
			else if ( JaxbAnyElement.class.isInstance( attributeElement ) ) {
				// todo : implement
			}
			else if ( JaxbOneToManyElement.class.isInstance( attributeElement ) ) {
				// todo : implement
			}
			else if ( JaxbManyToManyElement.class.isInstance( attributeElement ) ) {
				// todo : implement
			}
		}
		return attributeSources;
	}

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

	@Override
	public SingularAttributeNature getNature() {
		return SingularAttributeNature.COMPONENT;
	}

	@Override
	public ExplicitHibernateTypeSource getTypeInformation() {
		// <component/> does not support type information.
		return null;
	}

	@Override
	public String getName() {
		return componentElement.getName();
	}

	@Override
	public boolean isSingular() {
		return true;
	}

	@Override
	public String getPropertyAccessorName() {
		return componentElement.getAccess();
	}

	@Override
	public boolean isInsertable() {
		return componentElement.isInsert();
	}

	@Override
	public boolean isUpdatable() {
		return componentElement.isUpdate();
	}

	@Override
	public PropertyGeneration getGeneration() {
		// todo : is this correct here?
		return null;
	}

	@Override
	public boolean isLazy() {
		return componentElement.isLazy();
	}

	@Override
	public boolean isIncludedInOptimisticLocking() {
		return componentElement.isOptimisticLock();
	}

	@Override
	public Iterable<MetaAttributeSource> metaAttributes() {
		return Helper.buildMetaAttributeSources( componentElement.getMeta() );
	}

	@Override
	public boolean areValuesIncludedInInsertByDefault() {
		return isInsertable();
	}

	@Override
	public boolean areValuesIncludedInUpdateByDefault() {
		return isUpdatable();
	}

	@Override
	public boolean areValuesNullableByDefault() {
		return true;
	}

	@Override
	public List<RelationalValueSource> relationalValueSources() {
		// none, they are defined on the simple sub-attributes
		return null;
	}
}


text:
//package com.studio.jc.modules.mySys.security;
//
//import java.util.Collection;
//import java.util.List;
//
//import org.apache.commons.lang3.StringUtils;
//import org.apache.shiro.authc.AuthenticationException;
//import org.apache.shiro.authc.AuthenticationInfo;
//import org.apache.shiro.authc.AuthenticationToken;
//import org.apache.shiro.authc.SimpleAuthenticationInfo;
//import org.apache.shiro.authz.AuthorizationInfo;
//import org.apache.shiro.authz.SimpleAuthorizationInfo;
//import org.apache.shiro.realm.AuthorizingRealm;
//import org.apache.shiro.session.Session;
//import org.apache.shiro.subject.PrincipalCollection;
//import org.apache.shiro.util.ByteSource;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.stereotype.Service;
//
//import com.studio.jc.common.config.Global;
//import com.studio.jc.common.servlet.ValidateCodeServlet;
//import com.studio.jc.common.utils.Encodes;
//import com.studio.jc.common.utils.SpringContextHolder;
//import com.studio.jc.common.web.Servlets;
//import com.studio.jc.modules.member.vo.MemberVo;
//import com.studio.jc.modules.mySys.controller.MyLoginController;
//import com.studio.jc.modules.mySys.service.MySystemService;
//import com.studio.jc.modules.mySys.utils.MyUserUtils;
//import com.studio.jc.modules.mySys.vo.MyPermissionVo;
//import com.studio.jc.modules.mySys.vo.MyRoleVo;
//import com.studio.jc.modules.sys.entity.Menu;
//import com.studio.jc.modules.sys.entity.Role;
//import com.studio.jc.modules.sys.entity.User;
//import com.studio.jc.modules.sys.security.SystemAuthorizingRealm.Principal;
//import com.studio.jc.modules.sys.utils.LogUtils;
//import com.studio.jc.modules.sys.utils.UserUtils;
//
//
///**
// * 参照com.studio.jc.modules.sys.security.SystemAuthorizingRealm
// * @author chenjuncheng
// *
// */
//@Service
//public class MySystemAuthorizingRealm extends AuthorizingRealm{
//
//	private MySystemService mySystemService;
//
//	/**
//	 * 认证回调函数,登录时调用
//	 */
//	@Override
//	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken) {
//
//		MyUsernamePasswordToken token = (MyUsernamePasswordToken) authcToken;
//
//		//检查是否是验证码登录,isFail为false的时候只是检查登录的次数,如果超过三次,就
//		//要获取它的验证码,检查是否正确
//		if(MyLoginController.isValidateCodeLogin(token.getUsername(), false, false)){
//			Session session = MyUserUtils.getSession();
//			String code = (String)session.getAttribute(ValidateCodeServlet.VALIDATE_CODE);
//			if(null == token.getCaptcha() || !token.getCaptcha().toUpperCase().equals(code)){
//				throw new AuthenticationException("msg:验证码错误, 请重试.");
//			}
//		}
//		MySystemService mySystemService = getMySystemService();
//
//		MemberVo member = mySystemService.getMemberByLoginName(token.getUsername());
//
//		if(null != member){		//如果存在这个用户名
//			if(StringUtils.equals(member.getState(), "0")){
//				throw new AuthenticationException("msg:该账号禁止登陆。");
//			}
//			byte[] salt = Encodes.decodeHex(member.getPsw().substring(0, 16));
//			String pswSub = member.getPsw().substring(16);
//			ByteSource credentialsSalt = ByteSource.Util.bytes(salt);
//			String getName = getName();
//
//			return new SimpleAuthenticationInfo(new MyPrincipal(member),
//					pswSub, credentialsSalt, getName);
//
//		}else{
//			return null;
//		}
//
//	}
//
//	@Override
//	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
//
//		MyPrincipal principal = (MyPrincipal) getAvailablePrincipal(principals);
//
//		MemberVo member = getMySystemService().getMemberByLoginName(principal.getLoginName());
//
//		if(member != null){
//			SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
////			List<Menu> list = MyUserUtils.getMenuList();
//			//获取角色
//			List<MyRoleVo> roleList = MyUserUtils.getMyRoleList();
//			for(MyRoleVo role : roleList){
//				info.addRole(role.getRoleName());
//			}
//			//获取权限
//			List<MyPermissionVo> permissionList = MyUserUtils.getMyPermissionList();
//			for(MyPermissionVo permission : permissionList){
//				info.addStringPermission(permission.getPermissionUrl());
//			}
//			//如果需要记录登录记录的时候在这里修改登录记录
//
//			LogUtils.saveLog(Servlets.getRequest(), "系统登录");
//
//			return info;
//		}else{
//			return null;
//		}
//	}
//
//	/**
//	 * 获取系统业务对象
//	 */
//	public MySystemService getMySystemService() {
//		if (mySystemService == null){
//			mySystemService = SpringContextHolder.getBean(MySystemService.class);
//		}
//		return mySystemService;
//	}
//
//
//}


text:
ACCEPTED

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

#### Published in
Nova Hedwigia 27(3-4): 699 (1976)

#### Original name
Pseudotracylla dentata B. Sutton & Hodges, 1976

### Remarks
null


text:
from __future__ import absolute_import, division, print_function

from appr.api.gevent_app import GeventApp
from appr.commands.command_base import CommandBase

class RunServerCmd(CommandBase):
    name = 'run-server'
    help_message = 'Run the registry server (with gunicorn)'
    parse_unknown = False

    def __init__(self, options, unknown=None):
        super(RunServerCmd, self).__init__(options)
        self.options = options
        self.status = {}

    def _call(self):
        GeventApp(self.options).run()

    @classmethod
    def _add_arguments(cls, parser):
        parser.add_argument("-p", "--port", nargs="?", default=5000, type=int,
                            help="server port listen")
        parser.add_argument("-b", "--bind", nargs="?", default="0.0.0.0",
                            help="server bind address")
        parser.add_argument("--db-class", nargs="?", default="filesystem",
                            help="db class for storage")

    def _render_dict(self):
        return self.status

    def _render_console(self):
        return self.status['result']


text:
require 'pry'
require 'spec_helper'

RSpec.describe Spree::Stock::Estimator, :vcr do
  let(:estimator) { described_class.new shipment.order }
  let!(:shipment) { create :shipment }
  let(:package) { shipment.to_package }

  describe '#shipping_rates' do
    subject { estimator.shipping_rates package }

    context 'rates are found' do
      context 'shipping methods exist' do
        before { create_shipping_methods }

        it 'create no new shipping methods' do
          expect { subject }.to_not change { Spree::ShippingMethod.count }
        end

        context 'shipping methods are front end visible' do
          let(:rate_names) { ["USPS Express", "USPS First", "USPS ParcelSelect", "USPS Priority"] }
          let(:rate_costs) { [3.07, 5.54, 6.09, 25.21] }

          it 'has the correct names' do
            names = subject.map(&:name).sort
            expect(names).to eq rate_names
          end

          it 'has the correct costs' do
            costs = subject.map(&:cost).sort
            expect(costs).to eq rate_costs
          end
        end

        context 'shipping methods are not front end visible' do
          before { Spree::ShippingMethod.update_all display_on: :back_end }
          it { is_expected.to be_empty }
        end
      end

      context 'shipping methods dont exist' do
        it { is_expected.to be_empty } # new shipping methods are backend only

        it 'creates new shipping methods' do
          expect { subject }.to change { Spree::ShippingMethod.count }.by 4
        end
      end
    end

    context 'no rates are found' do
      let(:package) do
        instance_double(Spree::Stock::Package, easypost_shipment: fake_shipment)
      end

      let(:fake_shipment) do
        double(EasyPost::Shipment, rates: [])
      end

      it { is_expected.to be_empty }

      it 'create no new shipping methods' do
        expect { subject }.to_not change { Spree::ShippingMethod.count }
      end
    end
  end
end


text:
namespace net {
class IOBuffer;
}

namespace disk_cache {

class SimpleEntryImpl;

// SimpleEntryOperation stores the information regarding operations in
// SimpleEntryImpl, between the moment they are issued by users of the backend,
// and the moment when they are executed.
class SimpleEntryOperation {
 public:
  typedef net::CompletionOnceCallback CompletionOnceCallback;

  enum EntryOperationType {
    TYPE_OPEN = 0,
    TYPE_CREATE = 1,
    TYPE_OPEN_OR_CREATE = 2,
    TYPE_CLOSE = 3,
    TYPE_READ = 4,
    TYPE_WRITE = 5,
    TYPE_READ_SPARSE = 6,
    TYPE_WRITE_SPARSE = 7,
    TYPE_GET_AVAILABLE_RANGE = 8,
    TYPE_DOOM = 9,
  };

  // Whether an open/create method has returned an entry (optimistically)
  // already, or if it still needs to be delivered via a callback.
  enum EntryResultState {
    ENTRY_ALREADY_RETURNED = 0,
    ENTRY_NEEDS_CALLBACK = 1,
  };

  SimpleEntryOperation(SimpleEntryOperation&& other);
  ~SimpleEntryOperation();

  static SimpleEntryOperation OpenOperation(SimpleEntryImpl* entry,
                                            EntryResultState result_state,
                                            EntryResultCallback);
  static SimpleEntryOperation CreateOperation(SimpleEntryImpl* entry,
                                              EntryResultState result_state,
                                              EntryResultCallback);
  static SimpleEntryOperation OpenOrCreateOperation(
      SimpleEntryImpl* entry,
      OpenEntryIndexEnum index_state,
      EntryResultState result_state,
      EntryResultCallback);
  static SimpleEntryOperation CloseOperation(SimpleEntryImpl* entry);
  static SimpleEntryOperation ReadOperation(SimpleEntryImpl* entry,
                                            int index,
                                            int offset,
                                            int length,
                                            net::IOBuffer* buf,
                                            CompletionOnceCallback callback);
  static SimpleEntryOperation WriteOperation(SimpleEntryImpl* entry,
                                             int index,
                                             int offset,
                                             int length,
                                             net::IOBuffer* buf,
                                             bool truncate,
                                             bool optimistic,
                                             CompletionOnceCallback callback);
  static SimpleEntryOperation ReadSparseOperation(
      SimpleEntryImpl* entry,
      int64_t sparse_offset,
      int length,
      net::IOBuffer* buf,
      CompletionOnceCallback callback);
  static SimpleEntryOperation WriteSparseOperation(
      SimpleEntryImpl* entry,
      int64_t sparse_offset,
      int length,
      net::IOBuffer* buf,
      CompletionOnceCallback callback);
  static SimpleEntryOperation GetAvailableRangeOperation(
      SimpleEntryImpl* entry,
      int64_t sparse_offset,
      int length,
      RangeResultCallback callback);
  static SimpleEntryOperation DoomOperation(SimpleEntryImpl* entry,
                                            CompletionOnceCallback callback);

  EntryOperationType type() const {
    return static_cast<EntryOperationType>(type_);
  }
  CompletionOnceCallback ReleaseCallback() { return std::move(callback_); }
  EntryResultCallback ReleaseEntryResultCallback() {
    return std::move(entry_callback_);
  }
  RangeResultCallback ReleaseRangeResultCalback() {
    return std::move(range_callback_);
  }

  EntryResultState entry_result_state() { return entry_result_state_; }

  OpenEntryIndexEnum index_state() const { return index_state_; }
  int index() const { return index_; }
  int offset() const { return offset_; }
  int64_t sparse_offset() const { return sparse_offset_; }
  int length() const { return length_; }
  net::IOBuffer* buf() { return buf_.get(); }
  bool truncate() const { return truncate_; }
  bool optimistic() const { return optimistic_; }

 private:
  SimpleEntryOperation(SimpleEntryImpl* entry,
                       net::IOBuffer* buf,
                       CompletionOnceCallback callback,
                       int offset,
                       int64_t sparse_offset,
                       int length,
                       EntryOperationType type,
                       OpenEntryIndexEnum index_state,
                       int index,
                       bool truncate,
                       bool optimistic);

  // This ensures entry will not be deleted until the operation has ran.
  scoped_refptr<SimpleEntryImpl> entry_;
  scoped_refptr<net::IOBuffer> buf_;
  CompletionOnceCallback callback_;

  // Used in open and create operations.
  EntryResultCallback entry_callback_;
  EntryResultState entry_result_state_;

  // Used in write and read operations.
  const int offset_;
  const int64_t sparse_offset_;
  const int length_;

  // Used in get available range operations.
  RangeResultCallback range_callback_;

  const EntryOperationType type_;
  // Used in the "open or create" operation.
  const OpenEntryIndexEnum index_state_;
  // Used in write and read operations.
  const unsigned int index_;
  // Used only in write operations.
  const bool truncate_;
  const bool optimistic_;
};

}  // namespace disk_cache

#endif  // NET_DISK_CACHE_SIMPLE_SIMPLE_ENTRY_OPERATION_H_


text:
//*********************************************************//
//    Copyright (c) Microsoft. All rights reserved.
//
//    Apache 2.0 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.
//
//*********************************************************//

using Microsoft.VisualStudioTools.Project;
using Newtonsoft.Json.Linq;

namespace Microsoft.NodejsTools.Debugger.Serialization {
    sealed class NodeEvaluationVariable : INodeVariable {
        public NodeEvaluationVariable(NodeStackFrame stackFrame, string name, JToken message) {
            Utilities.ArgumentNotNull("name", name);
            Utilities.ArgumentNotNull("message", message);

            Id = (int)message["handle"];
            Parent = null;
            StackFrame = stackFrame;
            Name = name;
            TypeName = (string)message["type"];
            Value = (string)message["value"];
            Class = (string)message["className"];
            Text = (string)message["text"];
            Attributes = NodePropertyAttributes.None;
            Type = NodePropertyType.Normal;
        }

        public int Id { get; private set; }
        public NodeEvaluationResult Parent { get; private set; }
        public string Name { get; private set; }
        public string TypeName { get; private set; }
        public string Value { get; private set; }
        public string Class { get; private set; }
        public string Text { get; private set; }
        public NodePropertyAttributes Attributes { get; private set; }
        public NodePropertyType Type { get; private set; }
        public NodeStackFrame StackFrame { get; private set; }
    }
}


text:
function run_test()
{
  if (!("@mozilla.org/toolkit/crash-reporter;1" in Components.classes)) {
    dump("INFO | test_crash_runtimeabort.js | Can't test crashreporter in a non-libxul build.\n");
    return;
  }

  // Try crashing with a runtime abort
  do_crash(function() {
             crashType = CrashTestUtils.CRASH_RUNTIMEABORT;
             crashReporter.annotateCrashReport("TestKey", "TestValue");
           },
           function(mdump, extra) {
             do_check_eq(extra.TestKey, "TestValue");
             do_check_true(/xpcom_runtime_abort/.test(extra.Notes));
             do_check_false("OOMAllocationSize" in extra);
           },
          // process will exit with a zero exit status
          true);
}


text:
using Content.Shared.Materials;
using Content.Shared.Popups;
using Content.Server.Power.Components;
using Robust.Shared.Player;

namespace Content.Server.Materials;

/// <summary>
/// This handles <see cref="SharedMaterialStorageSystem"/>
/// </summary>
public sealed class MaterialStorageSystem : SharedMaterialStorageSystem
{
    [Dependency] private readonly SharedAudioSystem _audio = default!;
    [Dependency] private readonly SharedPopupSystem _popup = default!;

    public override bool TryInsertMaterialEntity(EntityUid user, EntityUid toInsert, EntityUid receiver, MaterialStorageComponent? component = null)
    {
        if (!Resolve(receiver, ref component))
            return false;
        if (TryComp<ApcPowerReceiverComponent>(receiver, out var power) && !power.Powered)
            return false;
        if (!base.TryInsertMaterialEntity(user, toInsert, receiver, component))
            return false;
        _audio.PlayPvs(component.InsertingSound, component.Owner);
        _popup.PopupEntity(Loc.GetString("machine-insert-item", ("user", user), ("machine", component.Owner),
            ("item", toInsert)), component.Owner, Filter.Pvs(component.Owner));
        QueueDel(toInsert);
        return true;
    }
}


text:
class IssueRelation < ActiveRecord::Base
  # Class used to represent the relations of an issue
  class Relations < Array
    include Redmine::I18n

    def initialize(issue, *args)
      @issue = issue
      super(*args)
    end

    def to_s(*args)
      map {|relation| "#{l(relation.label_for(@issue))} ##{relation.other_issue(@issue).id}"}.join(', ')
    end
  end

  belongs_to :issue_from, :class_name => 'Issue', :foreign_key => 'issue_from_id'
  belongs_to :issue_to, :class_name => 'Issue', :foreign_key => 'issue_to_id'

  TYPE_RELATES      = "relates"
  TYPE_DUPLICATES   = "duplicates"
  TYPE_DUPLICATED   = "duplicated"
  TYPE_BLOCKS       = "blocks"
  TYPE_BLOCKED      = "blocked"
  TYPE_PRECEDES     = "precedes"
  TYPE_FOLLOWS      = "follows"
  TYPE_COPIED_TO    = "copied_to"
  TYPE_COPIED_FROM  = "copied_from"

  TYPES = {
    TYPE_RELATES =>     { :name => :label_relates_to, :sym_name => :label_relates_to,
                          :order => 1, :sym => TYPE_RELATES },
    TYPE_DUPLICATES =>  { :name => :label_duplicates, :sym_name => :label_duplicated_by,
                          :order => 2, :sym => TYPE_DUPLICATED },
    TYPE_DUPLICATED =>  { :name => :label_duplicated_by, :sym_name => :label_duplicates,
                          :order => 3, :sym => TYPE_DUPLICATES, :reverse => TYPE_DUPLICATES },
    TYPE_BLOCKS =>      { :name => :label_blocks, :sym_name => :label_blocked_by,
                          :order => 4, :sym => TYPE_BLOCKED },
    TYPE_BLOCKED =>     { :name => :label_blocked_by, :sym_name => :label_blocks,
                          :order => 5, :sym => TYPE_BLOCKS, :reverse => TYPE_BLOCKS },
    TYPE_PRECEDES =>    { :name => :label_precedes, :sym_name => :label_follows,
                          :order => 6, :sym => TYPE_FOLLOWS },
    TYPE_FOLLOWS =>     { :name => :label_follows, :sym_name => :label_precedes,
                          :order => 7, :sym => TYPE_PRECEDES, :reverse => TYPE_PRECEDES },
    TYPE_COPIED_TO =>   { :name => :label_copied_to, :sym_name => :label_copied_from,
                          :order => 8, :sym => TYPE_COPIED_FROM },
    TYPE_COPIED_FROM => { :name => :label_copied_from, :sym_name => :label_copied_to,
                          :order => 9, :sym => TYPE_COPIED_TO, :reverse => TYPE_COPIED_TO }
  }.freeze

  validates_presence_of :issue_from, :issue_to, :relation_type
  validates_inclusion_of :relation_type, :in => TYPES.keys
  validates_numericality_of :delay, :allow_nil => true
  validates_uniqueness_of :issue_to_id, :scope => :issue_from_id
  validate :validate_issue_relation

  attr_protected :issue_from_id, :issue_to_id
  before_save :handle_issue_order
  after_create  :create_journal_after_create
  after_destroy :create_journal_after_delete

  def visible?(user=User.current)
    (issue_from.nil? || issue_from.visible?(user)) && (issue_to.nil? || issue_to.visible?(user))
  end

  def deletable?(user=User.current)
    visible?(user) &&
      ((issue_from.nil? || user.allowed_to?(:manage_issue_relations, issue_from.project)) ||
        (issue_to.nil? || user.allowed_to?(:manage_issue_relations, issue_to.project)))
  end

  def initialize(attributes=nil, *args)
    super
    if new_record?
      if relation_type.blank?
        self.relation_type = IssueRelation::TYPE_RELATES
      end
    end
  end

  def validate_issue_relation
    if issue_from && issue_to
      errors.add :issue_to_id, :invalid if issue_from_id == issue_to_id
      unless issue_from.project_id == issue_to.project_id ||
                Setting.cross_project_issue_relations?
        errors.add :issue_to_id, :not_same_project
      end
      # detect circular dependencies depending wether the relation should be reversed
      if TYPES.has_key?(relation_type) && TYPES[relation_type][:reverse]
        errors.add :base, :circular_dependency if issue_from.all_dependent_issues.include? issue_to
      else
        errors.add :base, :circular_dependency if issue_to.all_dependent_issues.include? issue_from
      end
      if issue_from.is_descendant_of?(issue_to) || issue_from.is_ancestor_of?(issue_to)
        errors.add :base, :cant_link_an_issue_with_a_descendant
      end
    end
  end

  def other_issue(issue)
    (self.issue_from_id == issue.id) ? issue_to : issue_from
  end

  # Returns the relation type for +issue+
  def relation_type_for(issue)
    if TYPES[relation_type]
      if self.issue_from_id == issue.id
        relation_type
      else
        TYPES[relation_type][:sym]
      end
    end
  end

  def label_for(issue)
    TYPES[relation_type] ?
        TYPES[relation_type][(self.issue_from_id == issue.id) ? :name : :sym_name] :
        :unknow
  end

  def css_classes_for(issue)
    "rel-#{relation_type_for(issue)}"
  end

  def handle_issue_order
    reverse_if_needed

    if TYPE_PRECEDES == relation_type
      self.delay ||= 0
    else
      self.delay = nil
    end
    set_issue_to_dates
  end

  def set_issue_to_dates
    soonest_start = self.successor_soonest_start
    if soonest_start && issue_to
      issue_to.reschedule_on!(soonest_start)
    end
  end

  def successor_soonest_start
    if (TYPE_PRECEDES == self.relation_type) && delay && issue_from &&
           (issue_from.start_date || issue_from.due_date)
      (issue_from.due_date || issue_from.start_date) + 1 + delay
    end
  end

  def <=>(relation)
    r = TYPES[self.relation_type][:order] <=> TYPES[relation.relation_type][:order]
    r == 0 ? id <=> relation.id : r
  end

  private

  # Reverses the relation if needed so that it gets stored in the proper way
  # Should not be reversed before validation so that it can be displayed back
  # as entered on new relation form
  def reverse_if_needed
    if TYPES.has_key?(relation_type) && TYPES[relation_type][:reverse]
      issue_tmp = issue_to
      self.issue_to = issue_from
      self.issue_from = issue_tmp
      self.relation_type = TYPES[relation_type][:reverse]
    end
  end

  def create_journal_after_create
    journal = issue_from.init_journal(User.current)
    journal.details << JournalDetail.new(:property => 'relation',
                                         :prop_key => relation_type_for(issue_from),
                                         :value    => issue_to.id)
    journal.save
    journal = issue_to.init_journal(User.current)
    journal.details << JournalDetail.new(:property => 'relation',
                                         :prop_key => relation_type_for(issue_to),
                                         :value    => issue_from.id)
    journal.save
  end

  def create_journal_after_delete
    journal = issue_from.init_journal(User.current)
    journal.details << JournalDetail.new(:property  => 'relation',
                                         :prop_key  => relation_type_for(issue_from),
                                         :old_value => issue_to.id)
    journal.save
    journal = issue_to.init_journal(User.current)
    journal.details << JournalDetail.new(:property  => 'relation',
                                         :prop_key  => relation_type_for(issue_to),
                                         :old_value => issue_from.id)
    journal.save
  end
end


text:
; <?php header("Location: https://".$_SERVER["HTTP_HOST"]); ?> prevents hacking
;required by ext_exec:
title = "Class Count"
page = "event_count.php"
height = "600"
width = "800"

;specific to this extension:
title_singular = "Class"
title_plural = "Classes"


text:
<!-- /#wrapper -->

    <!-- jQuery -->
    <script src="<?php echo base_url();?>assets/admin/js/jquery.js"></script>

    <!-- Bootstrap Core JavaScript -->
    <script src="<?php echo base_url();?>assets/admin/js/bootstrap.min.js"></script>

    <!-- Morris Charts JavaScript -->
    <script src="<?php echo base_url();?>assets/admin/js/plugins/morris/raphael.min.js"></script>
    <script src="<?php echo base_url();?>assets/admin/js/plugins/morris/morris.min.js"></script>
    <script src="<?php echo base_url();?>assets/admin/js/plugins/morris/morris-data.js"></script>

</body>

</html>


text:
from django.core.urlresolvers import reverse
from django.http.cookie import parse_cookie

from seahub.test_utils import BaseTestCase
from seahub.profile.models import Profile

class I18nTest(BaseTestCase):

    def test_can_set_to_zh(self):
        resp = self.client.get(reverse('i18n') + '?lang=zh-cn')
        self.assertEqual(302, resp.status_code)
        assert parse_cookie(resp.cookies)['django_language'] == 'zh-cn'

    def test_wrong_lang_code(self):
        resp = self.client.get(reverse('i18n') + '?lang=zh_CN')
        self.assertEqual(302, resp.status_code)
        assert parse_cookie(resp.cookies)['django_language'] == 'en'

    def test_anonymous_user_profile(self):
        # Should not add profile record when user is anonymous.
        resp = self.client.get(reverse('i18n') + '?lang=zh-cn')
        self.assertEqual(302, resp.status_code)
        assert len(Profile.objects.all()) == 0

    def test_add_new_user_profile(self):
        # Should add new profile record.
        self.login_as(self.user)

        resp = self.client.get(reverse('i18n') + '?lang=zh-cn')
        self.assertEqual(302, resp.status_code)
        assert len(Profile.objects.all()) == 1
        assert Profile.objects.get_user_language(self.user.username) == 'zh-cn'

    def test_update_user_profile(self):
        # Should update exist profile record.
        self.login_as(self.user)

        Profile.objects.add_or_update(self.user.username, 'nickname', 'intro')
        assert len(Profile.objects.all()) == 1

        resp = self.client.get(reverse('i18n') + '?lang=zh-cn')
        self.assertEqual(302, resp.status_code)
        assert len(Profile.objects.all()) == 1
        assert Profile.objects.get_user_language(self.user.username) == 'zh-cn'


text:
import { fixtures } from '../../../../../../admin-test-utils/lib';
import addLocaleToSingleTypesLinks from '../addLocaleToSingleTypesLinks';

describe('i18n | contentManagerHooks | addLocaleToSingleTypesLinks', () => {
  let store;

  beforeEach(() => {
    store = {
      ...fixtures.store.state,
      i18n_locales: { locales: [] },
    };
    store.rbacProvider.allPermissions = [];

    store.rbacProvider.collectionTypesRelatedPermissions = {
      test: {
        'plugin::content-manager.explorer.read': [],
        'plugin::content-manager.explorer.create': [],
      },
    };

    store.getState = function() {
      return this;
    };
  });

  it('should forward when the stLinks array is empty', () => {
    const data = {
      stLinks: [],
      models: [],
    };

    const results = addLocaleToSingleTypesLinks(data, store);

    expect(results).toEqual(data);
  });

  it('should not add the search key to a single type link when i18n is not enabled on the single type', () => {
    const data = {
      stLinks: [{ to: 'cm/singleType/test' }],
      models: [{ uid: 'test', pluginOptions: { i18n: { localized: false } } }],
    };

    const results = addLocaleToSingleTypesLinks(data, store);

    expect(results).toEqual(data);
  });

  it('should add a search key with the default locale when the user has the right to read it', () => {
    store.i18n_locales.locales = [{ code: 'en', isDefault: true }];
    store.rbacProvider.collectionTypesRelatedPermissions.test[
      'plugin::content-manager.explorer.read'
    ] = [{ properties: { locales: ['en'] } }];

    const data = {
      stLinks: [{ to: 'cm/singleType/test' }],
      models: [{ uid: 'test', pluginOptions: { i18n: { localized: true } } }],
    };

    const results = addLocaleToSingleTypesLinks(data, store);

    const expected = {
      stLinks: [{ to: 'cm/singleType/test', search: 'plugins[i18n][locale]=en' }],
      models: [{ uid: 'test', pluginOptions: { i18n: { localized: true } } }],
    };

    expect(results).toEqual(expected);
  });

  it('should set the isDisplayed key to false when the user does not have the right to read any locale', () => {
    store.i18n_locales.locales = [{ code: 'en', isDefault: true }];
    store.rbacProvider.collectionTypesRelatedPermissions.test[
      'plugin::content-manager.explorer.read'
    ] = [{ properties: { locales: [] } }];

    const data = {
      stLinks: [{ to: 'cm/singleType/test' }],
      models: [{ uid: 'test', pluginOptions: { i18n: { localized: true } } }],
    };
    const results = addLocaleToSingleTypesLinks(data, store);

    const expected = {
      stLinks: [{ to: 'cm/singleType/test', isDisplayed: false }],
      models: [{ uid: 'test', pluginOptions: { i18n: { localized: true } } }],
    };

    expect(results).toEqual(expected);
  });

  it('should keep the previous search', () => {
    store.i18n_locales.locales = [{ code: 'en', isDefault: true }];
    store.rbacProvider.collectionTypesRelatedPermissions.test[
      'plugin::content-manager.explorer.read'
    ] = [{ properties: { locales: ['en'] } }];

    const data = {
      stLinks: [{ to: 'cm/singleType/test', search: 'plugins[plugin][test]=test' }],
      models: [{ uid: 'test', pluginOptions: { i18n: { localized: true } } }],
    };
    const results = addLocaleToSingleTypesLinks(data, store);

    const expected = {
      stLinks: [
        {
          to: 'cm/singleType/test',
          search: 'plugins[plugin][test]=test&plugins[i18n][locale]=en',
        },
      ],
      models: [{ uid: 'test', pluginOptions: { i18n: { localized: true } } }],
    };

    expect(results).toEqual(expected);
  });
});


text:
#ifndef ES_TEXT_ITERATOR_H
#define ES_TEXT_ITERATOR_H

#include <unicode/ubrk.h>
// cf. http://icu-project.org/apiref/icu4c/ubrk_8h.html

namespace org { namespace w3c { namespace dom { namespace bootstrap {

class TextIterator
{
    UBreakIterator* bi;
    size_t current;
    size_t length;
public:
    TextIterator(UBreakIteratorType type = UBRK_LINE) :
        bi(0),
        current(UBRK_DONE),
        length(0)
    {
        UErrorCode err = U_ZERO_ERROR;
        bi = ubrk_open(UBRK_LINE, 0, 0, 0, &err);
        if (U_FAILURE(err))
            bi = 0;
    }
    ~TextIterator() {
        if (bi)
            ubrk_close(bi);
    }
    void setText(const char16_t* text, size_t length) {
        UErrorCode err = U_ZERO_ERROR;
        ubrk_setText(bi, reinterpret_cast<const UChar*>(text), length, &err);
        if (U_FAILURE(err)) {
            current = UBRK_DONE;
            return;
        }
        current = ubrk_first(bi);
        length = length;
    }
    bool next() {
        if (current != UBRK_DONE)
            current = ubrk_next(bi);
        return current != UBRK_DONE;
    }
    size_t operator*() {
        return current;
    }
    size_t size() const {
        return length;
    }
};

}}}}  // org::w3c::dom::bootstrap

#endif  // ES_TEXT_ITERATOR_H


text:
void Fatal(const char* msg, ...) {
  va_list ap;
  fprintf(stderr, "ninja: fatal: ");
  va_start(ap, msg);
  vfprintf(stderr, msg, ap);
  va_end(ap);
  fprintf(stderr, "\n");
#ifdef _WIN32
  // On Windows, some tools may inject extra threads.
  // exit() may block on locks held by those threads, so forcibly exit.
  fflush(stderr);
  fflush(stdout);
  ExitProcess(1);
#else
  exit(1);
#endif
}

void Warning(const char* msg, ...) {
  va_list ap;
  fprintf(stderr, "ninja: warning: ");
  va_start(ap, msg);
  vfprintf(stderr, msg, ap);
  va_end(ap);
  fprintf(stderr, "\n");
}

void Error(const char* msg, ...) {
  va_list ap;
  fprintf(stderr, "ninja: error: ");
  va_start(ap, msg);
  vfprintf(stderr, msg, ap);
  va_end(ap);
  fprintf(stderr, "\n");
}

bool CanonicalizePath(string* path, string* err) {
  METRIC_RECORD("canonicalize str");
  size_t len = path->size();
  char* str = 0;
  if (len > 0)
    str = &(*path)[0];
  if (!CanonicalizePath(str, &len, err))
    return false;
  path->resize(len);
  return true;
}

bool CanonicalizePath(char* path, size_t* len, string* err) {
  // WARNING: this function is performance-critical; please benchmark
  // any changes you make to it.
  METRIC_RECORD("canonicalize path");
  if (*len == 0) {
    *err = "empty path";
    return false;
  }

  const int kMaxPathComponents = 30;
  char* components[kMaxPathComponents];
  int component_count = 0;

  char* start = path;
  char* dst = start;
  const char* src = start;
  const char* end = start + *len;

  if (*src == '/') {
#ifdef _WIN32
    // network path starts with //
    if (*len > 1 && *(src + 1) == '/') {
      src += 2;
      dst += 2;
    } else {
      ++src;
      ++dst;
    }
#else
    ++src;
    ++dst;
#endif
  }

  while (src < end) {
    if (*src == '.') {
      if (src + 1 == end || src[1] == '/') {
        // '.' component; eliminate.
        src += 2;
        continue;
      } else if (src[1] == '.' && (src + 2 == end || src[2] == '/')) {
        // '..' component.  Back up if possible.
        if (component_count > 0) {
          dst = components[component_count - 1];
          src += 3;
          --component_count;
        } else {
          *dst++ = *src++;
          *dst++ = *src++;
          *dst++ = *src++;
        }
        continue;
      }
    }

    if (*src == '/') {
      src++;
      continue;
    }

    if (component_count == kMaxPathComponents)
      Fatal("path has too many components : %s", path);
    components[component_count] = dst;
    ++component_count;

    while (*src != '/' && src != end)
      *dst++ = *src++;
    *dst++ = *src++;  // Copy '/' or final \0 character as well.
  }

  if (dst == start) {
    *err = "path canonicalizes to the empty path";
    return false;
  }

  *len = dst - start - 1;
  return true;
}

int ReadFile(const string& path, string* contents, string* err) {
  FILE* f = fopen(path.c_str(), "r");
  if (!f) {
    err->assign(strerror(errno));
    return -errno;
  }

  char buf[64 << 10];
  size_t len;
  while ((len = fread(buf, 1, sizeof(buf), f)) > 0) {
    contents->append(buf, len);
  }
  if (ferror(f)) {
    err->assign(strerror(errno));  // XXX errno?
    contents->clear();
    fclose(f);
    return -errno;
  }
  fclose(f);
  return 0;
}

void SetCloseOnExec(int fd) {
#ifndef _WIN32
  int flags = fcntl(fd, F_GETFD);
  if (flags < 0) {
    perror("fcntl(F_GETFD)");
  } else {
    if (fcntl(fd, F_SETFD, flags | FD_CLOEXEC) < 0)
      perror("fcntl(F_SETFD)");
  }
#else
  HANDLE hd = (HANDLE) _get_osfhandle(fd);
  if (! SetHandleInformation(hd, HANDLE_FLAG_INHERIT, 0)) {
    fprintf(stderr, "SetHandleInformation(): %s", GetLastErrorString().c_str());
  }
#endif  // ! _WIN32
}

const char* SpellcheckStringV(const string& text,
                              const vector<const char*>& words) {
  const bool kAllowReplacements = true;
  const int kMaxValidEditDistance = 3;

  int min_distance = kMaxValidEditDistance + 1;
  const char* result = NULL;
  for (vector<const char*>::const_iterator i = words.begin();
       i != words.end(); ++i) {
    int distance = EditDistance(*i, text, kAllowReplacements,
                                kMaxValidEditDistance);
    if (distance < min_distance) {
      min_distance = distance;
      result = *i;
    }
  }
  return result;
}

const char* SpellcheckString(const string& text, ...) {
  va_list ap;
  va_start(ap, text);
  vector<const char*> words;
  const char* word;
  while ((word = va_arg(ap, const char*)))
    words.push_back(word);
  return SpellcheckStringV(text, words);
}

#ifdef _WIN32
string GetLastErrorString() {
  DWORD err = GetLastError();

  char* msg_buf;
  FormatMessageA(
        FORMAT_MESSAGE_ALLOCATE_BUFFER |
        FORMAT_MESSAGE_FROM_SYSTEM |
        FORMAT_MESSAGE_IGNORE_INSERTS,
        NULL,
        err,
        MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
        (char*)&msg_buf,
        0,
        NULL);
  string msg = msg_buf;
  LocalFree(msg_buf);
  return msg;
}

void Win32Fatal(const char* function) {
  Fatal("%s: %s", function, GetLastErrorString().c_str());
}
#endif

static bool islatinalpha(int c) {
  // isalpha() is locale-dependent.
  return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z');
}

string StripAnsiEscapeCodes(const string& in) {
  string stripped;
  stripped.reserve(in.size());

  for (size_t i = 0; i < in.size(); ++i) {
    if (in[i] != '\33') {
      // Not an escape code.
      stripped.push_back(in[i]);
      continue;
    }

    // Only strip CSIs for now.
    if (i + 1 >= in.size()) break;
    if (in[i + 1] != '[') continue;  // Not a CSI.
    i += 2;

    // Skip everything up to and including the next [a-zA-Z].
    while (i < in.size() && !islatinalpha(in[i]))
      ++i;
  }
  return stripped;
}

#if defined(linux) || defined(__GLIBC__)
int GetProcessorCount() {
  return get_nprocs();
}
#elif defined(__APPLE__) || defined(__FreeBSD__)
int GetProcessorCount() {
  int processors;
  size_t processors_size = sizeof(processors);
  int name[] = {CTL_HW, HW_NCPU};
  if (sysctl(name, sizeof(name) / sizeof(int),
             &processors, &processors_size,
             NULL, 0) < 0) {
    return 0;
  }
  return processors;
}
#elif defined(_WIN32)
int GetProcessorCount() {
  SYSTEM_INFO info;
  GetSystemInfo(&info);
  return info.dwNumberOfProcessors;
}
#else
// This is what get_nprocs() should be doing in the Linux implementation
// above, but in a more standard way.
int GetProcessorCount() {
  return sysconf(_SC_NPROCESSORS_ONLN);
}
#endif

#if defined(_WIN32) || defined(__CYGWIN__)
double GetLoadAverage() {
  // TODO(nicolas.despres@gmail.com): Find a way to implement it on Windows.
  // Remember to also update Usage() when this is fixed.
  return -0.0f;
}
#else
double GetLoadAverage() {
  double loadavg[3] = { 0.0f, 0.0f, 0.0f };
  if (getloadavg(loadavg, 3) < 0) {
    // Maybe we should return an error here or the availability of
    // getloadavg(3) should be checked when ninja is configured.
    return -0.0f;
  }
  return loadavg[0];
}
#endif // _WIN32

string ElideMiddle(const string& str, size_t width) {
  const int kMargin = 3;  // Space for "...".
  string result = str;
  if (result.size() + kMargin > width) {
    size_t elide_size = (width - kMargin) / 2;
    result = result.substr(0, elide_size)
      + "..."
      + result.substr(result.size() - elide_size, elide_size);
  }
  return result;
}


text:
module Atmosphere
  module MarkdownHelper
    def markdown(text)
      unless @markdown
        @markdown = Redcarpet::Markdown.new(Redcarpet::Render::HTML,
                        # see https://github.com/vmg/redcarpet#and-its-like-really-simple-to-use
                        no_intra_emphasis: true,
                        tables: true,
                        fenced_code_blocks: true,
                        autolink: true,
                        strikethrough: true,
                        lax_html_blocks: true,
                        space_after_headers: true,
                        superscript: true)
      end

      @markdown.render(text || '').html_safe
    end
  end
end


text:
<resources>
    <string name="app_name">TransparentScreen</string>
</resources>


text:
package org.sakaiproject.content.impl;

import org.sakaiproject.content.api.FileSystemHandler;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;

import org.springframework.util.FileCopyUtils;

/**
 * The default implementation of FileSystemHandler, targeting local disk.
 *
 * This class read and writes content files to local filesystem paths.
 */
public class DefaultFileSystemHandler implements FileSystemHandler {
    private boolean useIdForFilePath = false;

    /**
     * Default constructor.
     */
    public DefaultFileSystemHandler() {
    }

    /**
     * Whether to use the id for the file path.
     */
    public void setUseIdForFilePath(boolean useIdForFilePath){
        this.useIdForFilePath = useIdForFilePath;
    }

    /**
     * A Helper method to get the File object for the parameters.
     * This method will look at the property useIdForFilePath to see if the
     * id must be used in the file path.
     *
     * @param id The id of the resource.
     * @param root The root of the storage.
     * @param filePath The path to save the file to.
     * @return The File object.
     */
    private File getFile(String id, String root, String filePath){
        if (useIdForFilePath) {
            return new File(root, id);
        } else {
            return new File(root, filePath);
        }
    }

    @Override
    public InputStream getInputStream(String id, String root, String filePath) throws IOException {
        return new FileInputStream(getFile(id, root, filePath));
    }

    @Override
    public long saveInputStream(String id, String root, String filePath, InputStream stream) throws IOException {
        // Do not create the files for resources with zero length bodies
        if ((stream == null)) {
            return 0L;
        }

        // form the file name
        File file = getFile(id, root, filePath);

        // delete the old
        if (file.exists()) {
            file.delete();
        }

        // add the new
        // make sure all directories are there
        File parent = file.getParentFile();
        if (parent != null) {
            parent.mkdirs();
        }

        // write the file
        return FileCopyUtils.copy(stream, new FileOutputStream(file));
    }

    @Override
    public boolean delete(String id, String root, String filePath){
        File file = getFile(id, root, filePath);

        // delete
        if (file.exists()) {
            return file.delete();
        }
        return false;
    }

	@Override
	public URI getAssetDirectLink(String id, String root, String filePath) throws IOException {
		return null;
	}
}