text:
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Windows.Forms;

namespace basicphotoeditor
{
    public partial class Form1 : Form
    {
        /*
         * Form1
         *
         * Main UI form that contains all user-interface functionalities
         *
         * 14.5.2017 - Created by Samuli Kumo
         */

        private string TAG = "Form1"; //Use tag in debug messages to identify source class

        public Form1()
        {
            InitializeComponent();
            this.Text = Program.ProgramTitle; //Set window title to display app name
        }

        private void onClick(object sender, EventArgs e)
        {
            Button button = sender as Button;
            if (button == null)
            {
                return;
            }
            else if (button == buttonOpen)
            {
                Debug.WriteLine(TAG + ": buttonOpen: onClick()");
                openFileDialog();
            }
            else if(button == buttonSave)
            {
                //Show savefile dialog and save the file
                Debug.WriteLine(TAG + ": buttonSave: onClick()");
                //Fetch enabled settings and their values
                ProcessSettings settings = fetchSettings();
                //Open save dialog
                saveFileDialog(settings);
            }
        }

        private void openFileDialog()
        {   //This function initializes and opens file picker dialog
            Debug.WriteLine(TAG + ": openFileDialog()");
            this.openFileDialog1 = new OpenFileDialog();
            openFileDialog1.Title = "Select image file";
            openFileDialog1.Filter = "Image files |*.jpg;*.jpeg;*.png;*.tga;*.gif;*.tif;*.tiff;*.bmp"; //Limit selection to image files
            openFileDialog1.CheckFileExists = true;
            openFileDialog1.CheckPathExists = true;

            if(openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                string filepath = openFileDialog1.FileName;
                Debug.WriteLine(filepath);
                Program.setImagePath(filepath);
                updateUI();
            }
        }
        private void updateUI()
        {
            //Main UI
            setTextBox(Program.Image().getPath());

            //Resize
            int x = Program.getImageX();
            int y = Program.getImageY();
            double ratio = Program.getImageAspectRatio();
            string ratioFraction = Program.getImageAspectRatioAsFraction();
            textBoxResizeOrigX.Text = x.ToString();
            textBoxResizeOrigY.Text = y.ToString();
            textBoxResizeNewX.Text = x.ToString();
            textBoxResizeNewY.Text = y.ToString();
            labelResizeOldAspect.Text = ratioFraction;
            labelResizeNewAspect.Text = ratioFraction;

            //Color
            trackBarBrightness.Value = 0;
            trackBarContrast.Value = 0;
            trackBarSaturation.Value = 0;

            //Hue
            trackBarHue.Value = 0;

            //Rotate
            trackBarRotate.Value = 0;
        }

        private void openFileDialog1_FileOk(object sender, CancelEventArgs e)
        {
            Debug.WriteLine(TAG + ": openFileDialog1_FileOk()");
        }

        private void saveFileDialog(ProcessSettings settings)
        {
            //WORKAROUND: Because user can press Save button without raising FocusLeave() on textbox, call it here manually
            validateTextboxInput(textBoxResizeNewX);
            validateTextboxInput(textBoxResizeNewY);

            this.saveFileDialog1 = new SaveFileDialog();
            saveFileDialog1.Title = "Save image file";
            saveFileDialog1.Filter = "JPEG |*.JPG;*.JPEG|BMP|*.BMP;*.RLE|Compuserve GIF|*.GIF|TIFF|*.TIF;*.TIFF|PNG|*.PNG;*.PNS|Targa|*.TGA;*.VDA;*.ICB;*.VSB";

            if (saveFileDialog1.ShowDialog() == DialogResult.OK) //Filename cannot be blank
            {
                Program.saveImage(saveFileDialog1.FileName,settings);
            }
        }

        private void saveFileDialog_FileOk(object sender, CancelEventArgs e)
        {
            Debug.WriteLine(TAG + ":saveFileDialog_FileOk()");
        }

        private void setTextBox(string path)
        {
            this.textBoxFilepath.Text = path;
        }

        private ProcessSettings fetchSettings()
        {   //Store user-selected settings and values to ProcessSettings object
            ProcessSettings settings = new ProcessSettings();

            //Filters
            settings.filterGrayscale = checkBoxGrayscale.Checked;

            //Resize
            try
            {   //Check that new values are valid integers
                int x = int.Parse(textBoxResizeNewX.Text);
                int y = int.Parse(textBoxResizeNewY.Text);

                settings.resizeX = x;
                settings.resizeY = y;
                settings.resizeLockAspect = checkBoxResizeLockAspect.Checked;
                settings.resizeEnable = checkBoxResize.Checked;
            }
            catch(Exception e)
            {   //If X or Y values are not valid, do not resize
                Debug.WriteLine(TAG + ": " + e.Message);
                //Rollback values
                settings.resizeEnable = false;
                textBoxResizeNewX.Text = Program.getImageX().ToString();
                textBoxResizeNewY.Text = Program.getImageY().ToString();
            }

            //Color
            settings.colorAdjustEnable = checkBoxColour.Checked;
            settings.brightnessValue = trackBarBrightness.Value;
            settings.contrastValue = trackBarContrast.Value;
            settings.saturationValue = trackBarSaturation.Value;

            //Hue
            settings.hueEnable = checkBoxHue.Checked;
            settings.hueValue = 180 + trackBarHue.Value;
            settings.hueRotate = checkBoxHueRotate.Checked;

            //Rotation
            settings.rotateEnable = checkBoxRotate.Checked;
            settings.rotateValue = 180 + trackBarRotate.Value;

            return settings;
        }

        private void textboxFocusLeave(object sender, EventArgs e)
        {
            if (sender == null)
            {
                return;
            }
            if (sender == textBoxResizeNewX || sender == textBoxResizeNewY)
            {
                TextBox textbox = sender as TextBox;
                validateTextboxInput(textbox);
                return;
            }
            return;
        }

        private void validateTextboxInput(TextBox textbox)
        {   //This function can be called to check user input values for X and Y resolution and correct them if necessary
            if (textbox == textBoxResizeNewX)
            {
                try
                {
                    mMath mMath = new mMath();
                    int newX =  mMath.LimitToRange(int.Parse(textBoxResizeNewX.Text), Program.MinX, Program.MaxX); //Limit user input to permitted range

                    if (checkBoxResizeLockAspect.Checked)
                    {   //When aspect ratio is locked, automatically update Y-value to match X-input
                        double ratio = Program.getImageAspectRatio();
                        int newY = (int)Math.Round(newX / ratio);

                        if (newY < Program.MinY || newY > Program.MaxY)
                        {   //If newX is too large, it has to be constrained and newY recalculated
                            newY = new mMath().LimitToRange(newY, Program.MinY, Program.MaxY);
                            newX = (int)Math.Round(newY * ratio);

                        }
                        textBoxResizeNewX.Text = newX.ToString();
                        textBoxResizeNewY.Text = Math.Round(newX / ratio).ToString();
                        labelResizeNewAspect.Text = Program.getImageAspectRatioAsFraction(newX, newY);
                        return;
                    }else
                    {
                        int newY = int.Parse(textBoxResizeNewY.Text);
                        textBoxResizeNewX.Text = newX.ToString();
                        labelResizeNewAspect.Text = Program.getImageAspectRatioAsFraction(newX,newY);
                        return;
                    }
                }
                catch (Exception ex)
                {
                    Debug.WriteLine(TAG + ": " + ex.Message);
                }
            }
            else if (textbox == textBoxResizeNewY)
            {
                try
                {
                    mMath mMath = new mMath();
                    int newY = mMath.LimitToRange(int.Parse(textBoxResizeNewY.Text), Program.MinY, Program.MaxY);

                    if (checkBoxResizeLockAspect.Checked)
                    {   //When aspect ratio is locked, automatically update X-value to match Y-input
                        double ratio = Program.getImageAspectRatio();
                        int newX = (int)Math.Round(newY * ratio);

                        if (newX < Program.MinX || newX > Program.MaxX)
                        {   //If newX is too large, it has to be constrained and newY recalculated
                            newX = new mMath().LimitToRange(newX, Program.MinX, Program.MaxX); //check and clamp newX value if needed
                            newY = (int)Math.Round(newX / ratio);
                        }
                        textBoxResizeNewY.Text = newY.ToString();
                        textBoxResizeNewX.Text = newX.ToString();
                        labelResizeNewAspect.Text = Program.getImageAspectRatioAsFraction(newX, newY);
                        return;
                    }else
                    {
                        int newX = int.Parse(textBoxResizeNewX.Text);
                        double ratio = newX / newY;
                        textBoxResizeNewY.Text = newY.ToString();
                        labelResizeNewAspect.Text = Program.getImageAspectRatioAsFraction(newX, newY);
                        return;
                    }
                }
                catch (Exception ex)
                {
                    Debug.WriteLine(TAG + ": " + ex.Message);
                }
            }
        }

        private void trackBarScroll(object sender, EventArgs e)
        {
            TrackBar trackbar = sender as TrackBar;
            toolTipTrackbarValue.SetToolTip(trackbar, trackbar.Value.ToString());
        }

        private void checkboxMouseHover(object sender, EventArgs e)
        {
            CheckBox checkbox = sender as CheckBox;

            if(checkbox == checkBoxGrayscale)
            {
                toolTipInfo.SetToolTip(checkbox, "Convert image to grayscale");
            }
            else if(checkbox == checkBoxResize)
            {
                toolTipInfo.SetToolTip(checkbox, "Resize image");
            }
            else if (checkbox == checkBoxResizeLockAspect)
            {
                toolTipInfo.SetToolTip(checkbox, "Preserve original aspect ratio");
            }
            else if(checkbox == checkBoxColour)
            {
                toolTipInfo.SetToolTip(checkbox, "Adjust image color");
            }
            else if(checkbox == checkBoxHue)
            {
                toolTipInfo.SetToolTip(checkbox, "Adjust image hue");
            }
            else if(checkbox == checkBoxHueRotate)
            {
                toolTipInfo.SetToolTip(checkbox, "Enable to rotate hue for all colors");
            }
            else if(checkbox == checkBoxRotate)
            {
                toolTipInfo.SetToolTip(checkbox, "Rotate image");
            }

        }

        private void checkboxCheckedChanged(object sender, EventArgs e)
        {
            CheckBox checkbox = sender as CheckBox;

            if(checkbox == checkBoxResizeLockAspect)
            {   //When user locks aspect ratio, reset X and Y to baseline (original) values
                if (checkbox.Checked)
                {
                    textBoxResizeNewX.Text = Program.getImageX().ToString();
                    textBoxResizeNewY.Text = Program.getImageY().ToString();
                }
            }
        }

        private void textBoxMouseHover(object sender, EventArgs e)
        {
            TextBox textbox = sender as TextBox;

            if(textbox == textBoxResizeNewX)
            {
                toolTipInfo.SetToolTip(textbox, "1...8000");
            }
            else if(textbox == textBoxResizeNewY){
                toolTipInfo.SetToolTip(textbox, "1...8000");
            }
        }
    }
}


text:
/**
 * This middleware is responsible for authenticating the user requesting the route.
 * @param  {HTTP}     req  The request object
 * @param  {HTTP}     res  The response object
 * @param  {Function} next The next function of Javascript
 */
module.exports = function(req, res, next) {
    var jwt = require('jsonwebtoken');
    var User = require('../models/User').User;

    /* getting the token from the request headers */
    var token = req.headers.authorization;

    if (token) {
        /* validating the token */
        jwt.verify(token, process.env.JWT_SECRET, function(err, decoded) {
            if (err) {
                /* token is not valid */
                res.status(403).json({
                    status: 'Failed',
                    message: 'Authentication Error, token not valid'
                });

                return;
            }

            /* check that the token belongs to a user in the database */
            var id = decoded.userId;
            User.findOne({ _id: id }, function(err, user) {
                if (err) {
                    res.status(500).json({
                        status: 'Failed',
                        message: 'Internal Server Error'
                    });

                    console.error(err);
                    return;
                }

                if (user) {
                    /* token is valid, allow the user to continue */
                    req.user = user;
                    next();
                }
                else {
                    /* token doesn't belong to anyone in the database */
                    res.status(403).json({
                        status: 'Failed',
                        message: 'Authentication Error, token not valid'
                    });
                }
            });
        });
    }
    else {
        /* token is not provided */
        res.status(403).json({
            status: 'Failed',
            message: 'Authentication Error, token not provided'
        });
    }
};

redpajama_set_name: RedPajamaGithub


text:
import textwrap

from pyflakes import messages as m
from pyflakes.checker import (
    DoctestScope,
    FunctionScope,
    ModuleScope,
)
from pyflakes.test.test_other import Test as TestOther
from pyflakes.test.test_imports import Test as TestImports
from pyflakes.test.test_undefined_names import Test as TestUndefinedNames
from pyflakes.test.harness import TestCase, skip

class _DoctestMixin(object):

    withDoctest = True

    def doctestify(self, input):
        lines = []
        for line in textwrap.dedent(input).splitlines():
            if line.strip() == '':
                pass
            elif (line.startswith(' ') or
                  line.startswith('except:') or
                  line.startswith('except ') or
                  line.startswith('finally:') or
                  line.startswith('else:') or
                  line.startswith('elif ')):
                line = "... %s" % line
            else:
                line = ">>> %s" % line
            lines.append(line)
        doctestificator = textwrap.dedent('''\
            def doctest_something():
                """
                   %s
                """
            ''')
        return doctestificator % "\n       ".join(lines)

    def flakes(self, input, *args, **kw):
        return super(_DoctestMixin, self).flakes(self.doctestify(input), *args, **kw)

class Test(TestCase):

    withDoctest = True

    def test_scope_class(self):
        """Check that a doctest is given a DoctestScope."""
        checker = self.flakes("""
        m = None

        def doctest_stuff():
            '''
                >>> d = doctest_stuff()
            '''
            f = m
            return f
        """)

        scopes = checker.deadScopes
        module_scopes = [
            scope for scope in scopes if scope.__class__ is ModuleScope]
        doctest_scopes = [
            scope for scope in scopes if scope.__class__ is DoctestScope]
        function_scopes = [
            scope for scope in scopes if scope.__class__ is FunctionScope]

        self.assertEqual(len(module_scopes), 1)
        self.assertEqual(len(doctest_scopes), 1)

        module_scope = module_scopes[0]
        doctest_scope = doctest_scopes[0]

        self.assertIsInstance(doctest_scope, DoctestScope)
        self.assertIsInstance(doctest_scope, ModuleScope)
        self.assertNotIsInstance(doctest_scope, FunctionScope)
        self.assertNotIsInstance(module_scope, DoctestScope)

        self.assertIn('m', module_scope)
        self.assertIn('doctest_stuff', module_scope)

        self.assertIn('d', doctest_scope)

        self.assertEqual(len(function_scopes), 1)
        self.assertIn('f', function_scopes[0])

    def test_nested_doctest_ignored(self):
        """Check that nested doctests are ignored."""
        checker = self.flakes("""
        m = None

        def doctest_stuff():
            '''
                >>> def function_in_doctest():
                ...     \"\"\"
                ...     >>> ignored_undefined_name
                ...     \"\"\"
                ...     df = m
                ...     return df
                ...
                >>> function_in_doctest()
            '''
            f = m
            return f
        """)

        scopes = checker.deadScopes
        module_scopes = [
            scope for scope in scopes if scope.__class__ is ModuleScope]
        doctest_scopes = [
            scope for scope in scopes if scope.__class__ is DoctestScope]
        function_scopes = [
            scope for scope in scopes if scope.__class__ is FunctionScope]

        self.assertEqual(len(module_scopes), 1)
        self.assertEqual(len(doctest_scopes), 1)

        module_scope = module_scopes[0]
        doctest_scope = doctest_scopes[0]

        self.assertIn('m', module_scope)
        self.assertIn('doctest_stuff', module_scope)
        self.assertIn('function_in_doctest', doctest_scope)

        self.assertEqual(len(function_scopes), 2)

        self.assertIn('f', function_scopes[0])
        self.assertIn('df', function_scopes[1])

    def test_global_module_scope_pollution(self):
        """Check that global in doctest does not pollute module scope."""
        checker = self.flakes("""
        def doctest_stuff():
            '''
                >>> def function_in_doctest():
                ...     global m
                ...     m = 50
                ...     df = 10
                ...     m = df
                ...
                >>> function_in_doctest()
            '''
            f = 10
            return f

        """)

        scopes = checker.deadScopes
        module_scopes = [
            scope for scope in scopes if scope.__class__ is ModuleScope]
        doctest_scopes = [
            scope for scope in scopes if scope.__class__ is DoctestScope]
        function_scopes = [
            scope for scope in scopes if scope.__class__ is FunctionScope]

        self.assertEqual(len(module_scopes), 1)
        self.assertEqual(len(doctest_scopes), 1)

        module_scope = module_scopes[0]
        doctest_scope = doctest_scopes[0]

        self.assertIn('doctest_stuff', module_scope)
        self.assertIn('function_in_doctest', doctest_scope)

        self.assertEqual(len(function_scopes), 2)

        self.assertIn('f', function_scopes[0])
        self.assertIn('df', function_scopes[1])
        self.assertIn('m', function_scopes[1])

        self.assertNotIn('m', module_scope)

    def test_global_undefined(self):
        self.flakes("""
        global m

        def doctest_stuff():
            '''
                >>> m
            '''
        """, m.UndefinedName)

    def test_importBeforeDoctest(self):
        self.flakes("""
        import foo

        def doctest_stuff():
            '''
                >>> foo
            '''
        """)

    @skip("todo")
    def test_importBeforeAndInDoctest(self):
        self.flakes('''
        import foo

        def doctest_stuff():
            """
                >>> import foo
                >>> foo
            """

        foo
        ''', m.RedefinedWhileUnused)

    def test_importInDoctestAndAfter(self):
        self.flakes('''
        def doctest_stuff():
            """
                >>> import foo
                >>> foo
            """

        import foo
        foo()
        ''')

    def test_offsetInDoctests(self):
        exc = self.flakes('''

        def doctest_stuff():
            """
                >>> x # line 5
            """

        ''', m.UndefinedName).messages[0]
        self.assertEqual(exc.lineno, 5)
        self.assertEqual(exc.col, 12)

    def test_offsetInLambdasInDoctests(self):
        exc = self.flakes('''

        def doctest_stuff():
            """
                >>> lambda: x # line 5
            """

        ''', m.UndefinedName).messages[0]
        self.assertEqual(exc.lineno, 5)
        self.assertEqual(exc.col, 20)

    def test_offsetAfterDoctests(self):
        exc = self.flakes('''

        def doctest_stuff():
            """
                >>> x = 5
            """

        x

        ''', m.UndefinedName).messages[0]
        self.assertEqual(exc.lineno, 8)
        self.assertEqual(exc.col, 0)

    def test_syntaxErrorInDoctest(self):
        exceptions = self.flakes(
            '''
            def doctest_stuff():
                """
                    >>> from # line 4
                    >>>     fortytwo = 42
                    >>> except Exception:
                """
            ''',
            m.DoctestSyntaxError,
            m.DoctestSyntaxError,
            m.DoctestSyntaxError).messages
        exc = exceptions[0]
        self.assertEqual(exc.lineno, 4)
        self.assertEqual(exc.col, 26)
        exc = exceptions[1]
        self.assertEqual(exc.lineno, 5)
        self.assertEqual(exc.col, 16)
        exc = exceptions[2]
        self.assertEqual(exc.lineno, 6)
        self.assertEqual(exc.col, 18)

    def test_indentationErrorInDoctest(self):
        exc = self.flakes('''
        def doctest_stuff():
            """
                >>> if True:
                ... pass
            """
        ''', m.DoctestSyntaxError).messages[0]
        self.assertEqual(exc.lineno, 5)
        self.assertEqual(exc.col, 16)

    def test_offsetWithMultiLineArgs(self):
        (exc1, exc2) = self.flakes(
            '''
            def doctest_stuff(arg1,
                              arg2,
                              arg3):
                """
                    >>> assert
                    >>> this
                """
            ''',
            m.DoctestSyntaxError,
            m.UndefinedName).messages
        self.assertEqual(exc1.lineno, 6)
        self.assertEqual(exc1.col, 19)
        self.assertEqual(exc2.lineno, 7)
        self.assertEqual(exc2.col, 12)

    def test_doctestCanReferToFunction(self):
        self.flakes("""
        def foo():
            '''
                >>> foo
            '''
        """)

    def test_doctestCanReferToClass(self):
        self.flakes("""
        class Foo():
            '''
                >>> Foo
            '''
            def bar(self):
                '''
                    >>> Foo
                '''
        """)

    def test_noOffsetSyntaxErrorInDoctest(self):
        exceptions = self.flakes(
            '''
            def buildurl(base, *args, **kwargs):
                """
                >>> buildurl('/blah.php', ('a', '&'), ('b', '=')
                '/blah.php?a=%26&b=%3D'
                >>> buildurl('/blah.php', a='&', 'b'='=')
                '/blah.php?b=%3D&a=%26'
                """
                pass
            ''',
            m.DoctestSyntaxError,
            m.DoctestSyntaxError).messages
        exc = exceptions[0]
        self.assertEqual(exc.lineno, 4)
        exc = exceptions[1]
        self.assertEqual(exc.lineno, 6)

    def test_singleUnderscoreInDoctest(self):
        self.flakes('''
        def func():
            """A docstring

            >>> func()
            1
            >>> _
            1
            """
            return 1
        ''')

class TestOther(_DoctestMixin, TestOther):
    pass

class TestImports(_DoctestMixin, TestImports):

    def test_futureImport(self):
        """XXX This test can't work in a doctest"""

    def test_futureImportUsed(self):
        """XXX This test can't work in a doctest"""

class TestUndefinedNames(_DoctestMixin, TestUndefinedNames):

    def test_doubleNestingReportsClosestName(self):
        """
        Lines in doctest are a bit different so we can't use the test
        from TestUndefinedNames
        """
        exc = self.flakes('''
        def a():
            x = 1
            def b():
                x = 2 # line 7 in the file
                def c():
                    x
                    x = 3
                    return x
                return x
            return x
        ''', m.UndefinedLocal).messages[0]
        self.assertEqual(exc.message_args, ('x', 7))


text:
package database

// IMPLEMENTATION NOTES:
// - Encrypt PII separately from the main database.
// - Decrypt once to get all non-PII with encrypted PII, then decrypt each
//   individual PII (passwords, custom fields, etc.) as needed. This should
//   prevent more than one PII from existing in memory at a time.
// - Use simpler internal encryption so decryption of in-memory stuff is fast.
// - Use a "tags" format instead of folders (array of strings).
// - Allow easy integration with autotype-like tools via user scripts (plugins)
// - Use a sub-command style command line API.
// - Allow several password customization options (see
//   http://passwordsgenerator.net), arbitrary lengths, and the ability to
//   generate several passwords at once.
// - Include history for all modifications.

type databaseVersion int32

type Database struct {
	// Incremented every time the format changes so that migrations may be done.
	Version databaseVersion

	// A map of record id to record.
	Records map[UniqueId]*Record
}

// OPERATIONS:
// - Create
// - Where
// - Update
// - Delete


text:
"""
Configuration for cdn samples.
"""
# -*- coding: UTF-8 -*-

import logging
from baidubce.bce_client_configuration import BceClientConfiguration
from baidubce.auth.bce_credentials import BceCredentials

HOST = b'cdn.baidubce.com'
# online AK SK
SK = b''
AK = b''

logger = logging.getLogger('baidubce.services.cdn.cdnclient')
fh = logging.FileHandler('sample.log')
fh.setLevel(logging.DEBUG)

formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
fh.setFormatter(formatter)
logger.setLevel(logging.DEBUG)
logger.addHandler(fh)

config = BceClientConfiguration(credentials=BceCredentials(AK, SK), endpoint=HOST)
config.retry_policy.max_error_retry = 0


text:
<!doctype html>

	<meta charset="utf-8">
	<meta http-equiv="X-UA-Compatible" content="IE=edge">
	<title>ArrayLike | ninejs</title>
	<meta name="description" content="">
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<link rel="stylesheet" href="../assets/css/main.css">

						Search
						<input id="tsd-search-field" type="text" />

Preparing search index...

The search index is not available

					ninejs

						Options

								All

Public

Public/Protected

All

							<input type="checkbox" id="tsd-filter-inherited" checked />
							Inherited
							<input type="checkbox" id="tsd-filter-only-exported" />
							Only exported

					Menu

					Globals

					"core/array"

					ArrayLike

Interface ArrayLike

Hierarchy

						ArrayLike

Indexable

[name: string]: any

Index

Properties

length

Properties

length

length: number

Defined in core/array.ts:4

						Globals

						"core/array"

						Array<wbr>Like

								length

						filter

						for<wbr>Each

						index<wbr>Of

						map

Legend

Module

Object literal

Variable

Function

Function with type parameter

Index signature

Type alias

Enumeration

Enumeration member

Property

Method

Interface

Interface with type parameter

Constructor

Property

Method

Index signature

Class

Class with type parameter

Constructor

Property

Method

Accessor

Index signature

Inherited constructor

Inherited property

Inherited method

Inherited accessor

Protected property

Protected method

Protected accessor

Private property

Private method

Private accessor

Static property

Static method

Generated using TypeDoc


text:
require 'test/unit'
require_relative '../../test_helper'
class BitmessageTest < Test::Unit::TestCase
  def test_get_messages
    api = Bitmessage::ApiClient.new ENV['BM_URI']
    result = api.add 1, 1
    assert_equal 2, result
  end
end


text:
#ifndef WebWorkerClient_h
#define WebWorkerClient_h

#include "WebCommon.h"

namespace WebKit {
    class WebString;
    class WebWorker;

    // Provides an interface back to the in-page script object for a worker.
    // All functions are expected to be called back on the thread that created
    // the Worker object, unless noted.
    class WebWorkerClient {
    public:
        virtual void postMessageToWorkerObject(const WebString&) = 0;

        virtual void postExceptionToWorkerObject(
            const WebString& errorString, int lineNumber,
            const WebString& sourceURL) = 0;

        virtual void postConsoleMessageToWorkerObject(
            int destinationIdentifier,
            int sourceIdentifier,
            int messageLevel,
            const WebString& message,
            int lineNumber,
            const WebString& sourceURL) = 0;

        virtual void confirmMessageFromWorkerObject(bool hasPendingActivity) = 0;
        virtual void reportPendingActivity(bool hasPendingActivity) = 0;

        virtual void workerContextDestroyed() = 0;

        // This can be called on any thread to create a nested worker.
        virtual WebKit::WebWorker* createWorker(WebKit::WebWorkerClient* client) = 0;
    };

} // namespace WebKit

#endif


text:
@interface MOBProjectionEPSG2485 : MOBProjection

@end


text:
package com.wavesplatform.transaction.assets.exchange

import com.wavesplatform.account.{Address, KeyPair, PrivateKey, PublicKey}
import com.wavesplatform.common.state.ByteStr
import com.wavesplatform.crypto
import com.wavesplatform.lang.ValidationError
import com.wavesplatform.transaction.*
import com.wavesplatform.transaction.Asset.Waves
import com.wavesplatform.transaction.TxValidationError.GenericError
import com.wavesplatform.transaction.assets.exchange.Order.Version
import com.wavesplatform.transaction.assets.exchange.Validation.booleanOperators
import com.wavesplatform.transaction.serialization.impl.OrderSerializer
import monix.eval.Coeval
import play.api.libs.json.{Format, JsObject}

import scala.util.Try

sealed trait OrderAuthentication
object OrderAuthentication {
  final case class OrderProofs(key: PublicKey, proofs: Proofs) extends OrderAuthentication
  final case class Eip712Signature(signature: ByteStr)         extends OrderAuthentication

  def apply(pk: PublicKey): OrderProofs = OrderProofs(pk, Proofs.empty)
}

/** Order to matcher service for asset exchange
  */
case class Order(
    version: Version,
    orderAuthentication: OrderAuthentication,
    matcherPublicKey: PublicKey,
    assetPair: AssetPair,
    orderType: OrderType,
    amount: TxExchangeAmount,
    price: TxOrderPrice,
    timestamp: TxTimestamp,
    expiration: TxTimestamp,
    matcherFee: TxMatcherFee,
    matcherFeeAssetId: Asset = Waves,
    priceMode: OrderPriceMode = OrderPriceMode.Default
) extends Proven {
  import Order.*

  lazy val senderPublicKey: PublicKey = orderAuthentication match {
    case OrderAuthentication.OrderProofs(publicKey, _)  => publicKey
    case OrderAuthentication.Eip712Signature(signature) => EthOrders.recoverEthSignerKey(this, signature.arr)
  }

  val eip712Signature: Option[ByteStr] = orderAuthentication match {
    case OrderAuthentication.Eip712Signature(signature) => Some(signature)
    case OrderAuthentication.OrderProofs(_, _)          => None
  }

  val proofs: Proofs = orderAuthentication match {
    case OrderAuthentication.OrderProofs(_, proofs) => proofs
    case OrderAuthentication.Eip712Signature(_)     => Proofs.empty
  }

  lazy val sender: PublicKey      = senderPublicKey
  def senderAddress: Address = sender.toAddress

  def withProofs(proofs: Proofs): Order = {
    copy(orderAuthentication = OrderAuthentication.OrderProofs(senderPublicKey, proofs))
  }

  def isValid(atTime: Long): Validation = {
    assetPair.isValid &&
    (timestamp > 0) :| "timestamp should be > 0" &&
    (expiration - atTime <= MaxLiveTime) :| "expiration should be earlier than 30 days" &&
    (expiration >= atTime) :| "expiration should be > currentTime" &&
    (matcherFeeAssetId == Waves || version >= Order.V3) :| "matcherFeeAssetId should be waves" &&
    (version > 0 && version < 5) :| "invalid version" &&
    (eip712Signature.isEmpty || version >= Order.V4) :| "eip712Signature available only in V4" &&
    eip712Signature.forall(es => es.size == 65 || es.size == 129) :| "eip712Signature should be of length 65 or 129" &&
    (version >= Order.V4 || priceMode == OrderPriceMode.Default) :| s"price mode should be default for V$version" &&
    (orderAuthentication match {
      case OrderAuthentication.OrderProofs(_, proofs) =>
        Proofs.validate(proofs).fold(e => Validation.failure(e.toString), _ => Validation.success)
      case _ => Validation.success
    })
  }

  def isValidAmount(matchAmount: Long, matchPrice: Long): Validation = {
    (matchAmount > 0) :| "amount should be > 0" &&
    (matchPrice > 0) :| "price should be > 0" &&
    (matchAmount < MaxAmount) :| "amount too large"
  }

  val bodyBytes: Coeval[Array[Byte]] = Coeval.evalOnce(OrderSerializer.bodyBytes(this))
  val id: Coeval[ByteStr]            = Coeval.evalOnce(ByteStr(crypto.fastHash(bodyBytes())))
  val idStr: Coeval[String]          = Coeval.evalOnce(id().toString)

  /** @note
    *   Shouldn't be used for orders >= V4
    */
  val bytes: Coeval[Array[Byte]] = Coeval.evalOnce(OrderSerializer.toBytes(this))

  def getReceiveAssetId: Asset = orderType match {
    case OrderType.BUY  => assetPair.amountAsset
    case OrderType.SELL => assetPair.priceAsset
  }

  def getSpendAssetId: Asset = orderType match {
    case OrderType.BUY  => assetPair.priceAsset
    case OrderType.SELL => assetPair.amountAsset
  }

  val json: Coeval[JsObject] = Coeval.evalOnce(OrderSerializer.toJson(this))

  override def toString: String = {
    val matcherFeeAssetIdStr = if (version == 3) s" matcherFeeAssetId=${matcherFeeAssetId.fold("Waves")(_.toString)}," else ""
    s"OrderV$version(id=${idStr()}, sender=$senderPublicKey, matcher=$matcherPublicKey, pair=$assetPair, type=$orderType, amount=$amount, " +
      s"price=$price, priceMode=$priceMode, ts=$timestamp, exp=$expiration, fee=$matcherFee,$matcherFeeAssetIdStr, eip712Signature=$eip712Signature, proofs=$proofs)"
  }
}

object Order {
  type Id      = ByteStr
  type Version = Byte

  implicit lazy val jsonFormat: Format[Order] = com.wavesplatform.transaction.assets.exchange.OrderJson.orderFormat

  val MaxLiveTime: Long = 30L * 24L * 60L * 60L * 1000L
  val PriceConstant     = 100000000L
  val MaxAmount: Long   = 100 * PriceConstant * PriceConstant

  val V1: Version = 1.toByte
  val V2: Version = 2.toByte
  val V3: Version = 3.toByte
  val V4: Version = 4.toByte

  implicit def sign(order: Order, privateKey: PrivateKey): Order =
    order.withProofs(Proofs(crypto.sign(privateKey, order.bodyBytes())))

  def selfSigned(
      version: TxVersion,
      sender: KeyPair,
      matcher: PublicKey,
      assetPair: AssetPair,
      orderType: OrderType,
      amount: Long,
      price: Long,
      timestamp: TxTimestamp,
      expiration: TxTimestamp,
      matcherFee: Long,
      matcherFeeAssetId: Asset = Asset.Waves,
      priceMode: OrderPriceMode = OrderPriceMode.Default
  ): Either[ValidationError, Order] =
    for {
      amount     <- TxExchangeAmount(amount)(GenericError(s"Order validation error: ${TxExchangeAmount.errMsg}"))
      price      <- TxOrderPrice(price)(GenericError(s"Order validation error: ${TxOrderPrice.errMsg}"))
      matcherFee <- TxMatcherFee(matcherFee)(GenericError(s"Order validation error: ${TxMatcherFee.errMsg}"))
    } yield {
      Order(
        version,
        OrderAuthentication(sender.publicKey),
        matcher,
        assetPair,
        orderType,
        amount,
        price,
        timestamp,
        expiration,
        matcherFee,
        matcherFeeAssetId,
        priceMode = priceMode
      )
        .signWith(sender.privateKey)
    }

  def buy(
      version: TxVersion,
      sender: KeyPair,
      matcher: PublicKey,
      pair: AssetPair,
      amount: Long,
      price: Long,
      timestamp: TxTimestamp,
      expiration: TxTimestamp,
      matcherFee: Long,
      matcherFeeAssetId: Asset = Waves,
      priceMode: OrderPriceMode = OrderPriceMode.Default
  ): Either[ValidationError, Order] =
    Order.selfSigned(version, sender, matcher, pair, OrderType.BUY, amount, price, timestamp, expiration, matcherFee, matcherFeeAssetId, priceMode)

  def sell(
      version: TxVersion,
      sender: KeyPair,
      matcher: PublicKey,
      pair: AssetPair,
      amount: Long,
      price: Long,
      timestamp: TxTimestamp,
      expiration: TxTimestamp,
      matcherFee: Long,
      matcherFeeAssetId: Asset = Waves,
      priceMode: OrderPriceMode = OrderPriceMode.Default
  ): Either[ValidationError, Order] =
    Order.selfSigned(version, sender, matcher, pair, OrderType.SELL, amount, price, timestamp, expiration, matcherFee, matcherFeeAssetId, priceMode)

  def parseBytes(version: Version, bytes: Array[Byte]): Try[Order] =
    OrderSerializer.parseBytes(version, bytes)
}


text:
'use strict';

// MODULES //

var readFile = require( 'utils-fs-read-file' ),
	parse = require( 'utils-hjson-parse' ),
	isString = require( 'validate.io-string-primitive' );

// READ SYNC //

/**
* FUNCTION: readSync( path[, options] )
*	Reads the entire contents of a Human JSON file.
*
* @param {String} path - file path
* @param {Object|String} [options] - function options
* @returns {Object|Error} JSON object or an error
*/
function readSync( path, options ) {
	var file,
		opts;

	if (
		arguments.length > 1 &&
		!isString( options )
	) {
		opts = options;
	} else {
		opts = {};
	}
	opts.encoding = 'utf8';
	file = readFile.sync( path, opts );
	if ( file instanceof Error ) {
		return file;
	}
	return parse( file );
} // end FUNCTION readSync()

// EXPORTS //

module.exports = readSync;


text:
import Entity from "entity/Entity";
import { Stat } from "entity/IStats";
import { Events, IEventEmitter } from "event/EventEmitter";
import Component from "newui/component/Component";
interface IInspectEntityInformationSubsectionEvents extends Events<Component> {
    change(): any;
    switchTo(): any;
    switchAway(): any;
}
export default abstract class InspectEntityInformationSubsection extends Component {
    event: IEventEmitter<this, IInspectEntityInformationSubsectionEvents>;
    constructor();
    abstract update(entity: Entity): void;
    getImmutableStats(): Stat[];
}
export {};


text:
package com.plugin.commons.user;

import org.xinhua.analytics.analytics.AnalyticsAgent;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;

import com.plugin.R;
import com.plugin.commons.ComApp;
import com.plugin.commons.helper.ComUtil;
import com.plugin.commons.helper.DialogUtil;
import com.plugin.commons.helper.FuncUtil;
import com.plugin.commons.helper.SituoHttpAjax;
import com.plugin.commons.helper.SituoHttpAjax.SituoAjaxCallBack;
import com.plugin.commons.helper.XHConstants;
import com.plugin.commons.helper.XHSDKUtil;
import com.plugin.commons.model.RspResultModel;
import com.plugin.commons.service.UserInfoService;
import com.plugin.commons.service.UserInfoServiceImpl;
import com.plugin.commons.ui.main.MainActivity;
import com.zq.types.StBaseType;

public class RegisterSetPwdActivity extends Activity{
	public final static String PARAMS_SMSCODE = "smscode";
	public final static String PARAMS_MOBILE = "mobile";
	EditText et_pwd;
	EditText et_pwd2;
	Button btn_sure;
	String mMobile = "";
	String mSmsCode = "";
	UserInfoService userService;
	public void onCreate(Bundle savedInstanceState) {
		requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_setpwd);
		ComUtil.customeTitle(this, getResources().getString(R.string.zh_setpwd),true);
		if (getIntent().getExtras() != null && getIntent().getExtras().containsKey(PARAMS_SMSCODE)) {
			mSmsCode =getIntent().getExtras().getString(PARAMS_SMSCODE);
		}
		if (getIntent().getExtras() != null && getIntent().getExtras().containsKey(PARAMS_MOBILE)) {
			mMobile =getIntent().getExtras().getString(PARAMS_MOBILE);
		}
		userService = new UserInfoServiceImpl();
		initProper();
		ensureUI();
	}

	private void initProper(){
		et_pwd = (EditText)findViewById(R.id.et_pwd);
		et_pwd2 = (EditText)findViewById(R.id.et_pwd2);
		btn_sure = (Button)findViewById(R.id.btn_sure);
		btn_sure.setBackgroundResource(ComApp.getInstance().appStyle.btn_sign_selector);
	}

	private void ensureUI(){
		btn_sure.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				final String pwd = et_pwd.getText().toString();
				final String pwd2 = et_pwd2.getText().toString();
				if(FuncUtil.isEmpty(pwd)){
					DialogUtil.showToast(RegisterSetPwdActivity.this, "请输入密码");
					return ;
				}
				if(FuncUtil.isEmpty(pwd2)){
					DialogUtil.showToast(RegisterSetPwdActivity.this, "请输入确认密码");
					return ;
				}
				if(!pwd.equals(pwd2)){
					DialogUtil.showToast(RegisterSetPwdActivity.this, "两次输入密码不一致");
					return ;
				}
				DialogUtil.showProgressDialog(RegisterSetPwdActivity.this);
				SituoHttpAjax.ajax(new SituoAjaxCallBack(){

					@Override
					public StBaseType requestApi() {
						// TODO Auto-generated method stub
						RspResultModel rsp = userService.register(mMobile, pwd, mSmsCode);
						return rsp;
					}

					@Override
					public void callBack(StBaseType baseType) {
						DialogUtil.closeProgress(RegisterSetPwdActivity.this);
						// TODO Auto-generated method stub
						RspResultModel rsp = (RspResultModel)baseType;
						if(ComUtil.checkRsp(RegisterSetPwdActivity.this, rsp)){
							//用户行为采集
							XHSDKUtil.addXHBehavior(RegisterSetPwdActivity.this,mMobile, XHConstants.XHTOPIC_REGISTER,mMobile+" register success");
							Intent intent = new Intent(RegisterSetPwdActivity.this,MainActivity.class);
							intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
							startActivity(intent);
							finish();
						}
					}

				});
			}
		});
	}
	@Override
	public void onResume() {
		super.onResume();
		AnalyticsAgent.onResume(this);//新华sdk
	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		AnalyticsAgent.onPause(this);//新华sdk
	}

}


text:
OC.L10N.register(
    "updatenotification",
    {
    "Update notifications" : "Tilkynningar um uppfærslu",
    "{version} is available. Get more information on how to update." : "{version} er í boði. Fáðu frekari upplýsingar um hvernig á að uppfæra.",
    "Updated channel" : "Uppfærði rás",
    "ownCloud core" : "ownCloud kjarna",
    "Update for %1$s to version %2$s is available." : "Upfærsla %1$s í útgáfu %2$s er tiltæk.",
    "Updater" : "Uppfærslustýring",
    "A new version is available: %s" : "Ný útgáfa er tiltæk: %s",
    "Open updater" : "Opna uppfærslustýringu",
    "Show changelog" : "Sýna breytingaskrá",
    "Your version is up to date." : "Útgáfan þín er af nýjustu gerð.",
    "Checked on %s" : "Athugað þann %s",
    "Update channel:" : "Uppfærslurás:",
    "You can always update to a newer version / experimental channel. But you can never downgrade to a more stable channel." : "Þú getur alltaf uppfært í nýrri útgáfu eða tilraunaútgáfurás. En þú getur aldrei niðurfært í stöðugri rás.",
    "Notify members of the following groups about available updates:" : "Tilkynna meðlimum eftirfarandi hópa um tiltækar uppfærslur:",
    "Only notification for app updates are available, because the selected update channel for ownCloud itself does not allow notifications." : "Eingöngu eru eru tiltækar tilkynningar fyrir uppfærslur forrita, vegna þess að valin uppfærslurás fyrir sjálft ownCloud leyfir ekki tilkynningar."
},
"nplurals=2; plural=(n % 10 != 1 || n % 100 == 11);");


text:
using System;

namespace IBM.Data.DB2
{

	public class DB2ClientUtils
	{

		#region DB2CheckReturn

		public static void DB2CheckReturn(short sqlRet, short handleType, IntPtr handle, string message, DB2Connection connection)
		{
			switch (sqlRet)
			{
				case DB2Constants.SQL_SUCCESS_WITH_INFO:
					if(connection != null)
					{
						connection.OnInfoMessage(handleType, handle);
					}
					goto case DB2Constants.SQL_SUCCESS;
				case DB2Constants.SQL_SUCCESS:
				case DB2Constants.SQL_NO_DATA:
					return;

				case DB2Constants.SQL_INVALID_HANDLE:
					throw new ArgumentException("Invalid handle");

				default:
				case DB2Constants.SQL_ERROR:
					throw new DB2Exception(handleType, handle, message);
			}
		}
		public static void DB2CheckReturn(short sqlRet, short handleType, IntPtr handle, string message)
		{
			DB2CheckReturn(sqlRet, handleType, handle, message, null);
		}
		#endregion
	}
}


text:
from __future__ import absolute_import
from django.conf import settings

import os

from celery import Celery
from celery.schedules import crontab

# set the default Django settings module for the 'celery' program.
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'aliendb.settings')

app = Celery('aliendb')
app.config_from_object('django.conf:settings')
app.autodiscover_tasks(lambda: settings.INSTALLED_APPS)

# define schedule for periodic tasks
app.conf.beat_schedule = {
    'update-submissions': {
        'task': 'aliendb.apps.analytics.tasks.get_top_submissions',
        'schedule': 1200.0,
        'args': ()
    },
}
app.conf.timezone = 'UTC'


text:
#include "anim.hpp"
#include "dialog_scene.hpp"
#include "play_scene.hpp"

#define BUTTON_FONT_SCALE 0.6f
#define TEXT_FONT_SCALE 0.6f
#define BUTTON_MARGIN 0.1f

#define BUTTON_WIDTH 0.4f
#define BUTTON_HEIGHT 0.15f
#define BUTTON_SIZE BUTTON_WIDTH, BUTTON_HEIGHT
#define BUTTON_COLOR 0.0f, 1.0f, 0.0f
#define BUTTON_DISCOURAGE_COLOR 0.0f, 0.4f, 0.0f
#define LEFT_X center * 2 * 0.33f
#define RIGHT_X center * 2 * 0.67f
#define TEXT_Y 0.6f

DialogScene::DialogScene() {
    mLeftButtonId = mRightButtonId = -1;
    mTextBoxId = -1;
    mLeftButtonAction = mRightButtonAction = ACTION_RETURN;
    mButtonY = 0.5f;
    mText = mLeftButtonText = mRightButtonText = NULL;
}

DialogScene::~DialogScene() {
}

void DialogScene::CreateWidgetsSetText() {
    const char *text = mText;
    float center = 0.5f * SceneManager::GetInstance()->GetScreenAspect();

    if (mTextBoxId < 0) {
        mTextBoxId = NewWidget()->SetTransition(UiWidget::TRANS_FROM_TOP)->GetId();
    }

    GetWidgetById(mTextBoxId)->SetText(text)->SetFontScale(TEXT_FONT_SCALE)
            ->SetCenter(center, TEXT_Y);

    float height = TextRenderer::MeasureTextHeight(text, TEXT_FONT_SCALE);
    mButtonY = TEXT_Y - height * 0.5f - BUTTON_MARGIN - 0.5f * BUTTON_HEIGHT;
}

void DialogScene::CreateWidgetsSingleButton() {
    const char *text = mLeftButtonText;
    int action = mLeftButtonAction;
    float center = 0.5f * SceneManager::GetInstance()->GetScreenAspect();
    mLeftButtonId = NewWidget()->SetText(text)->SetIsButton(true)->SetCenter(center, mButtonY)
            ->SetSize(BUTTON_SIZE)->SetTextColor(BUTTON_COLOR)->SetFontScale(BUTTON_FONT_SCALE)
            ->SetTransition(UiWidget::TRANS_FROM_BOTTOM)->GetId();
    mLeftButtonAction = action;

    SetDefaultButton(mLeftButtonId);
}

void DialogScene::CreateWidgetsTwoButtons() {
    const char *leftText = mLeftButtonText;
    int leftAction = mLeftButtonAction;
    const char *rightText = mRightButtonText;
    int rightAction = mRightButtonAction;

    float center = 0.5f * SceneManager::GetInstance()->GetScreenAspect();
    mLeftButtonId = NewWidget()->SetText(leftText)->SetIsButton(true)->SetCenter(LEFT_X, mButtonY)
            ->SetSize(BUTTON_SIZE)->SetTextColor(BUTTON_COLOR)
            ->SetTransition(UiWidget::TRANS_FROM_LEFT)->GetId();
    mLeftButtonAction = leftAction;
    mRightButtonId = NewWidget()->SetText(rightText)->SetIsButton(true)
            ->SetCenter(RIGHT_X, mButtonY)->SetSize(BUTTON_SIZE)
            ->SetTransition(UiWidget::TRANS_FROM_RIGHT)
            ->SetTextColor(BUTTON_COLOR)->GetId();
    mRightButtonAction = rightAction;

    if (leftAction == ACTION_SIGN_OUT || leftAction == ACTION_PLAY_WITHOUT_SIGNIN) {
        GetWidgetById(mLeftButtonId)->SetTextColor(BUTTON_DISCOURAGE_COLOR);
    }
    if (rightAction == ACTION_SIGN_OUT || rightAction == ACTION_PLAY_WITHOUT_SIGNIN) {
        GetWidgetById(mRightButtonId)->SetTextColor(BUTTON_DISCOURAGE_COLOR);
    }

    // set up navigation between the buttons
    AddNav(mLeftButtonId, UI_DIR_RIGHT, mRightButtonId);
    AddNav(mRightButtonId, UI_DIR_LEFT, mLeftButtonId);
}

void DialogScene::OnCreateWidgets() {
    if (mRightButtonText) {
        CreateWidgetsSetText();
        CreateWidgetsTwoButtons();
    } else {
        CreateWidgetsSetText();
        CreateWidgetsSingleButton();
    }
}

void DialogScene::RenderBackground() {
    RenderBackgroundAnimation(mShapeRenderer);
}

bool DialogScene::OnBackKeyPressed() {
    SceneManager *mgr = SceneManager::GetInstance();
    mgr->RequestNewScene(new WelcomeScene());
    return true;
}

void DialogScene::OnButtonClicked(int id) {
    SceneManager *mgr = SceneManager::GetInstance();

    int action;
    if (id == mLeftButtonId) {
        action = mLeftButtonAction;
    } else if (id == mRightButtonId) {
        action = mRightButtonAction;
    } else {
        return;
    }

    switch (action) {
        case ACTION_RETURN:
            mgr->RequestNewScene(new WelcomeScene());
            break;
        case ACTION_SIGN_IN:
            // note: we can't start playing directly because PlayScene expects the cloud
            // results to be ready when it constructs itself; therefore, WelcomeScene
            // has to make sure of that. So we can't jump directly to PlayScene from here.
            mgr->RequestNewScene(new WelcomeScene());
            break;
        case ACTION_PLAY_WITHOUT_SIGNIN:
            mgr->RequestNewScene(new PlayScene());
            break;
        case ACTION_SIGN_OUT:
            mgr->RequestNewScene(new WelcomeScene());
            break;
        default:
            // do nothing.
            break;
    }
}


text:
package main

import (
	"compress/gzip"
	"fmt"
	"io"
	"log"
	"math"
	"os"
	"path/filepath"
	"strings"
	"time"

	"github.com/influxdata/influxdb/influxql"
	"github.com/influxdata/influxdb/models"
	"github.com/influxdata/influxdb/tsdb/engine/tsm1"
)

type cmdExport struct {
	path            string
	out             string
	db              string
	retentionPolicy string
	startTime       int64
	endTime         int64
	compress        bool

	ext   string
	files map[string][]string
}

func newCmdExport(path, out, db, retentionPolicy, startTime, endTime string, compress bool) (*cmdExport, error) {
	var start, end int64
	if startTime != "" {
		s, err := time.Parse(time.RFC3339, startTime)
		if err != nil {
			return nil, err
		}
		start = s.UnixNano()
	} else {
		start = math.MinInt64
	}
	if endTime != "" {
		e, err := time.Parse(time.RFC3339, endTime)
		if err != nil {
			return nil, err
		}
		end = e.UnixNano()
	} else {
		// set end time to max if it is not set.
		end = math.MaxInt64
	}

	return &cmdExport{
		path:            filepath.Join(path, "data"),
		out:             out,
		db:              db,
		compress:        compress,
		ext:             fmt.Sprintf(".%s", tsm1.TSMFileExtension),
		retentionPolicy: retentionPolicy,
		startTime:       start,
		endTime:         end,
		files:           make(map[string][]string),
	}, nil
}

func (c *cmdExport) validate() error {
	// validate args
	if c.retentionPolicy != "" && c.db == "" {
		return fmt.Errorf("must specify a db")
	}
	if c.startTime != 0 && c.endTime != 0 && c.endTime < c.startTime {
		return fmt.Errorf("end time before start time")
	}
	return nil
}

func (c *cmdExport) run() error {
	if err := c.validate(); err != nil {
		return err
	}

	return c.export()
}

func (c *cmdExport) export() error {
	if err := c.walkFiles(); err != nil {
		return err
	}
	return c.writeFiles()
}

func (c *cmdExport) walkFiles() error {
	err := filepath.Walk(c.path, func(path string, f os.FileInfo, err error) error {
		if err != nil {
			return err
		}
		if filepath.Ext(path) == c.ext {
			//files = append(files, path)
			relPath, _ := filepath.Rel(c.path, path)
			dirs := strings.Split(relPath, string(byte(os.PathSeparator)))
			if dirs[0] == c.db || c.db == "" {
				if dirs[1] == c.retentionPolicy || c.retentionPolicy == "" {
					key := filepath.Join(dirs[0], dirs[1])
					files := c.files[key]
					if files == nil {
						files = []string{}
					}
					c.files[key] = append(files, path)
				}
			}
		}
		return nil
	})
	if err != nil {
		log.Fatal(err)
	}
	return nil
}

func (c *cmdExport) writeFiles() error {
	// open our output file and create an output buffer
	var w io.WriteCloser
	w, err := os.Create(c.out)
	if err != nil {
		return err
	}
	defer w.Close()
	if c.compress {
		w = gzip.NewWriter(w)
		defer w.Close()
	}

	s, e := time.Unix(0, c.startTime).Format(time.RFC3339), time.Unix(0, c.endTime).Format(time.RFC3339)
	fmt.Fprintf(w, "# INFLUXDB EXPORT: %s - %s\n", s, e)

	// Write out all the DDL
	fmt.Fprintln(w, "# DDL")
	for key := range c.files {
		keys := strings.Split(key, string(byte(os.PathSeparator)))
		db, rp := influxql.QuoteIdent(keys[0]), influxql.QuoteIdent(keys[1])
		fmt.Fprintf(w, "CREATE DATABASE %s WITH NAME %s\n", db, rp)
	}

	fmt.Fprintln(w, "# DML")
	for key, files := range c.files {
		keys := strings.Split(key, string(byte(os.PathSeparator)))
		fmt.Fprintf(w, "# CONTEXT-DATABASE:%s\n", keys[0])
		fmt.Fprintf(w, "# CONTEXT-RETENTION-POLICY:%s\n", keys[1])
		for _, f := range files {
			// use an anonymous function here to close the files in the defers and not let them
			// accumulate in the loop
			if err := func(f string) error {
				file, err := os.OpenFile(f, os.O_RDONLY, 0600)
				if err != nil {
					return fmt.Errorf("%v", err)
				}
				defer file.Close()
				reader, err := tsm1.NewTSMReader(file)
				if err != nil {
					log.Printf("unable to read %s, skipping\n", f)
					return nil
				}
				defer reader.Close()

				if sgStart, sgEnd := reader.TimeRange(); sgStart > c.endTime || sgEnd < c.startTime {
					return nil
				}

				for i := 0; i < reader.KeyCount(); i++ {
					var pairs string
					key, typ := reader.KeyAt(i)
					values, _ := reader.ReadAll(string(key))
					measurement, field := tsm1.SeriesAndFieldFromCompositeKey(key)

					for _, value := range values {
						if (value.UnixNano() < c.startTime) || (value.UnixNano() > c.endTime) {
							continue
						}

						switch typ {
						case tsm1.BlockFloat64:
							pairs = field + "=" + fmt.Sprintf("%v", value.Value())
						case tsm1.BlockInteger:
							pairs = field + "=" + fmt.Sprintf("%vi", value.Value())
						case tsm1.BlockBoolean:
							pairs = field + "=" + fmt.Sprintf("%v", value.Value())
						case tsm1.BlockString:
							pairs = field + "=" + fmt.Sprintf("%q", models.EscapeStringField(fmt.Sprintf("%s", value.Value())))
						default:
							pairs = field + "=" + fmt.Sprintf("%v", value.Value())
						}

						fmt.Fprintln(w, string(measurement), pairs, value.UnixNano())
					}
				}
				return nil
			}(f); err != nil {
				return err
			}
		}
		_ = key
	}
	return nil
}


text:
import { Component } from '@angular/core';

@Component({
    selector: 'projectes-page',
    templateUrl: './projectes.component.html'
})
export class ProjectesPageContainer {
    public projects;
    public arrayProjects: Array<Object>;
    constructor() {
        this.projects = require('./projects.json');
        this.arrayProjects = [];
        for (var key in this.projects) {
            if (this.projects.hasOwnProperty(key)) {
                let element = this.projects[key],
                    project = {
                        country: key,
                        list: element
                    };
                this.arrayProjects.push(project);
            }
        }
    }

}


text:
var BaseUser = require('framework/base/baseUser');
var LobbyUser = BaseUser.extend({
	init : function(uid) {
		this._super(uid);
		this.gameId = 0;
		this.gameServerId = "";
	},
	onGetUserInfo : function(){

	},
	onEnterGame : function(gameId,reEnterInfo,targetServerId){
        this.gameId = gameId;
        this.reEnterInfo = reEnterInfo;
        this.gameServerId = targetServerId;
	},
	onLeaveGame : function(){
		this.gameId = 0;
        this.reEnterInfo = {};
        this.gameServerId = "";
	},
	getUserShowInfo : function() {
		if (!F.isset(this.userInfo)){
			//返回错误信息
			return {
				uid : this.userInfo.uid,
				uname : '[未知]',
				avatar_url : '',
				avatar_id : 0,
				level : 0,
				vip_level: 0
			}

		}
		return {
			uid : this.userInfo.uid,
			uname : this.userInfo.uname,
			avatar_url : this.userInfo.avatar_url,
			avatar_id : this.userInfo.avatar_id,
			level : this.userInfo.level,
			vip_level: this.userInfo.vip_level,
		}
	},
	getSendToGameInfo : function() {
		if (!F.isset(this.userInfo)){
			//返回错误信息
			return {
				uid : this.userInfo.uid,
				uname : '[未知]',
				avatar_url : '',
				avatar_id : 0,
				credits : 0,
				total_credits : 0,
				level : 0,
				vip_level: 0,
				exp : 0,
				is_robot : 0
			}

		}
		return {
			uid : this.userInfo.uid,
			uname : this.userInfo.uname,
			avatar_url : this.userInfo.avatar_url,
			avatar_id : this.userInfo.avatar_id,
			credits : this.userInfo.credits,
			total_credits : this.userInfo.total_credits,
			level : this.userInfo.level,
			vip_level: this.userInfo.vip_level,
			exp : 0,
			is_robot : this.userInfo.is_robot
		}
	},
});
module.exports = LobbyUser;


text:
	public function validateStrongPassword(password:String):Boolean
	{
		if (password == null || password.length <= 0)
		{
			return false;
		}

		return STRONG_PASSWORD_PATTERN.test(password);
	}


text:
package internal.org.springframework.content.jpa.boot.autoconfigure;

import org.springframework.boot.jdbc.AbstractDataSourceInitializer;
import org.springframework.boot.jdbc.DataSourceInitializationMode;
import org.springframework.core.io.ResourceLoader;
import org.springframework.util.Assert;

import javax.annotation.PostConstruct;
import javax.sql.DataSource;

public class ContentJpaDatabaseInitializer extends AbstractDataSourceInitializer {

	private ContentJpaProperties properties;

	public ContentJpaDatabaseInitializer(DataSource ds, ResourceLoader resourceLoader,
			ContentJpaProperties properties) {
		super(ds, resourceLoader);
		Assert.notNull(properties, "ContentJpaProperties must not be null");
		this.properties = properties;
	}

	@PostConstruct
	public void initialize() {
		super.initialize();
	}

	@Override
	protected DataSourceInitializationMode getMode() {
		return properties.getInitializer().getInitializeSchema();
	}

	@Override
	protected String getSchemaLocation() {
		return properties.getSchema();
	}
}


text:
<?xml version="1.0" encoding="UTF-8"?>

<document xmlns="http://maven.apache.org/XDOC/2.0"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/XDOC/2.0 http://maven.apache.org/xsd/xdoc-2.0.xsd">

  <properties>
    <title>Fast</title>
    <author email="roland@jolokia.org">Roland Huss</author>
  </properties>

        Before praising Jolokia to be the fasted remote JMX
        solution on the world,
        it has to be confessed, that we don't have any hard benchmarks
        yet. But this is something on the todo list.

        Jolokia is especially a very fast JMX remote accessing
        solution for non-Java environments since for a client there is
        no need to start a JVM which needs some time to
        startup. E.g. most of the Nagios JMX plugins out there,
        require a local JVM installation and the plugins, which are
        implemented in Java, queries the MBeans via JSR-160 and prints
        out the results to standard output for a single check, opening
        a new connection for each request. For large Nagios
        installations which monitors hundreds of servers for several
        parameters this poses a performance problem. With Jolokia, it
        has been confirmed that it scales up very well in a Nagios
        environment with 500 servers monitoring about 10 parameters on
        each server every 5 minutes.

        Especially bulk requests can
        speed up monitoring considerably. This unique feature, which
        is not available for JSR-160 connectors, allows for quering
        many parameters with a single server turnaround.

        Jolokia uses the super fast JSON serialization
        library json-simple. Along with the fact that
        JSON itself is a very compact data format with small overhead
        compared to RMI, this adds to the good performance experience.

        In summary, all these facts indicate that the Jolokia is
        faster than standard JSR-160 connectors with communication of
        RMI. A benchmark is pending to put these statements on a solid
        ground.

      <subsection name="Next">

            Jolokia is simple. Really.

            See why how Jolokia can secure JMX access in a very fine granular way.

            Go Back to the Features Overview.

      </subsection>

</document>


text:
<mat-spinner></mat-spinner>

Connection lost...


text:
using ::testing::NiceMock;

namespace espv2 {
namespace envoy {
namespace token {
namespace test {

class MockTokenSubscriberFactory : public TokenSubscriberFactory {
 public:
  MOCK_METHOD(TokenSubscriberPtr, createImdsTokenSubscriber,
              (const TokenType& token_type, const std::string& token_cluster,
               const std::string& token_url, std::chrono::seconds fetch_timeout,
               ::espv2::api::envoy::v11::http::common::DependencyErrorBehavior
                   error_behavior,
               UpdateTokenCallback callback),
              (const));

  MOCK_METHOD(
      TokenSubscriberPtr, createIamTokenSubscriber,
      (const TokenType& token_type, const std::string& token_cluster,
       const std::string& token_url, std::chrono::seconds fetch_timeout,
       ::espv2::api::envoy::v11::http::common::DependencyErrorBehavior
           error_behavior,
       UpdateTokenCallback callback,
       const ::google::protobuf::RepeatedPtrField<std::string>& delegates,
       const ::google::protobuf::RepeatedPtrField<std::string>& scopes,
       GetTokenFunc access_token_fn),
      (const));
};

class MockTokenInfo : public TokenInfo {
 public:
  MOCK_METHOD(Envoy::Http::RequestMessagePtr, prepareRequest,
              (absl::string_view token_url), (const));

  MOCK_METHOD(bool, parseAccessToken,
              (absl::string_view response, TokenResult* ret), (const));

  MOCK_METHOD(bool, parseIdentityToken,
              (absl::string_view response, TokenResult* ret), (const));
};

using MockTokenInfoPtr = std::unique_ptr<NiceMock<MockTokenInfo>>;

}  // namespace test
}  // namespace token
}  // namespace envoy
}  // namespace espv2


text:
#include "py/objexcept.h"
#include "py/objstr.h"
#include "py/parsenum.h"
#include "py/runtime.h"
#include "shared-bindings/socketpool/__init__.h"
#include "shared-bindings/socketpool/Socket.h"
#include "shared-bindings/socketpool/SocketPool.h"

//| """
//| The `socketpool` module provides sockets through a pool. The pools themselves
//| act like CPython's `socket` module.
//|
//| For more information about the `socket` module, see the CPython documentation:
//| https://docs.python.org/3/library/socket.html
//| """

STATIC const mp_rom_map_elem_t socketpool_globals_table[] = {
    { MP_ROM_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_socketpool) },

    { MP_ROM_QSTR(MP_QSTR_SocketPool), MP_ROM_PTR(&socketpool_socketpool_type) },
    { MP_ROM_QSTR(MP_QSTR_Socket), MP_ROM_PTR(&socketpool_socket_type) },
};

STATIC MP_DEFINE_CONST_DICT(socketpool_globals, socketpool_globals_table);

const mp_obj_module_t socketpool_module = {
    .base = { &mp_type_module },
    .globals = (mp_obj_dict_t *)&socketpool_globals,
};

MP_REGISTER_MODULE(MP_QSTR_socketpool, socketpool_module, CIRCUITPY_SOCKETPOOL);


text:
package fr.synchrotron.soleil.ica.ci.lib.mongodb.domainobjects.artifact.ext;

/**
 * @author Gregory Boissinot
 */
public class ArtifactDocumentForC {

    private String archi;

    private String platform;

    private String compiler;

    private String typeDep;

    private String mod;

    public ArtifactDocumentForC(String archi, String platform, String compiler, String typeDep, String mod) {
        this.archi = archi;
        this.platform = platform;
        this.compiler = compiler;
        this.typeDep = typeDep;
        this.mod = mod;
    }

    public String getArchi() {
        return archi;
    }

    public void setArchi(String archi) {
        this.archi = archi;
    }

    public String getPlatform() {
        return platform;
    }

    public void setPlatform(String platform) {
        this.platform = platform;
    }

    public String getCompiler() {
        return compiler;
    }

    public void setCompiler(String compiler) {
        this.compiler = compiler;
    }

    public String getTypeDep() {
        return typeDep;
    }

    public void setTypeDep(String typeDep) {
        this.typeDep = typeDep;
    }

    public String getMod() {
        return mod;
    }

    public void setMod(String mod) {
        this.mod = mod;
    }
}


text:
namespace SingleplayerEngine.Audio.Sfml
{
    public enum AudioFlag
    {
        NoError,
        Disposable
    }
}


text:
package com.leetcode.onlinejudge.problems._0_olds.v1._3_string;

import com.leetcode.interfaces.IProblem;
import com.leetcode.onlinejudge.BaseProblem;

/**
 * Created by Who on 2014/8/7.
 */
public class _41_String_to_Integer_atoi extends BaseProblem implements IProblem {
    @Override
    public int getVersion() {
        return 1;
    }

    @Override
    public String getSummary() {
        return "Implement atoi to convert a string to an integer.\n" +
                "Hint: Carefully consider all possible input cases. If you want a challenge, please do not see below and ask yourself what are the possible input cases.\n" +
                "Notes: It is intended for this problem to be specified vaguely (ie, no given input specs). You are responsible to gather all the input requirements up front.\n" +
                "Requirements for atoi:\n" +
                "The function first discards as many whitespace characters as necessary until the first non-whitespace character is found. Then, starting from this character, takes an optional initial plus or minus sign followed by as many numerical digits as possible, and interprets them as a numerical value.\n" +
                "The string can contain additional characters after those that form the integral number, which are ignored and have no effect on the behavior of this function.\n" +
                "If the first sequence of non-whitespace characters in str is not a valid integral number, or if no such sequence exists because either str is empty or it contains only whitespace characters, no conversion is performed.\n" +
                "If no valid conversion could be performed, a zero value is returned. If the correct value is out of the range of representable values, INT_MAX (2147483647) or INT_MIN (-2147483648) is returned.";
    }

    @Override
    public void run() {
        print(new Solution().atoi("+431"));
    }

    public class Solution {
        public int atoi(String str) {
            if (str.trim().length() == 0)
                return 0;
            char[] chars = str.trim().toCharArray();
            int num = 0;
            int len = chars.length;
            int i = 0;
            int sign = 1;
            if (chars[0] == '+')
                i++;
            if (chars[0] == '-') {
                sign = -1;
                i++;
            }
            for (; i < len; i++) {
                if (chars[i] < '0' || chars[i] > '9')
                    break;
                if (num > Integer.MAX_VALUE / 10 || num == Integer.MAX_VALUE / 10 && chars[i] - '0' > Integer.MAX_VALUE % 10)
                    return sign == -1 ? Integer.MIN_VALUE : Integer.MAX_VALUE;
                num = num * 10 + chars[i] - '0';
            }
            return num * sign;
        }
    }
}


text:
.. image:: logo/horizontal.svg
   :width: 400px
   :alt: django-sesame

django-sesame provides frictionless authentication with "Magic Links" for
your Django project.

It generates URLs containing authentication tokens such as:
https://example.com/?sesame=zxST9d0XT9xgfYLvoa9e2myN

Then it authenticates users based on tokens found in URLs.

More broadly, it supports a wide range of `use cases`_ for
stateless, token-based authentication.

Please review `(in)security`_ considerations before using django-sesame.

----

`Documentation is available on ReadTheDocs.`__

----

__ https://django-sesame.readthedocs.io/en/stable/

Requirements
------------

django-sesame is tested with:

- Django 3.2 (LTS), 4.0, and 4.1;
- Python ≥ 3.6.

It requires ``django.contrib.auth``.

Getting started
---------------

Install django-sesame:

.. code-block:: console

    $ pip install django-sesame

Open your project settings and add ``"sesame.backends.ModelBackend"`` to the
``AUTHENTICATION_BACKENDS`` setting. Extending the default value, this
looks like:

.. code-block:: python

    AUTHENTICATION_BACKENDS = [
        "django.contrib.auth.backends.ModelBackend",
        "sesame.backends.ModelBackend",
    ]

Now, your project can authenticate users based on django-sesame tokens.

Quick example
-------------

Configure ``LoginView`` in your URLconf:

.. code-block:: python

    from django.urls import path
    from sesame.views import LoginView

    urlpatterns = [
        ...,
        path("sesame/login/", LoginView.as_view(), name="sesame-login"),
        ...,
    ]

Load a user from the database:

.. code-block:: pycon

    >>> from django.contrib.auth import get_user_model
    >>> User = get_user_model()
    >>> user = User.objects.first()

Generate a login URL for this user:

.. code-block:: pycon

    >>> from sesame.utils import get_query_string
    >>> LOGIN_URL = "https://127.0.0.1:8000/sesame/login/"
    >>> LOGIN_URL + get_query_string(user)
    'https://127.0.0.1:8000/sesame/login/?sesame=zxST9d0XT9xgfYLvoa9e2myN'

(Your token will be different from this example.)

Make sure that you're logged out. Open the login URL. You are logged in!

Use cases
---------

Known use cases for django-sesame include:

1. Login by email, an attractive option on mobile where typing passwords
   is uncomfortable. This technique is prominently deployed by Slack.

   If you're doing this, you should define a small ``SESAME_MAX_AGE``, perhaps
   10 minutes.

2. Authenticated links. For example, you can generate a report offline
   and, when it's ready, email a link to access it. Authenticated links work
   even if the user isn't logged in on the device where they're opening it.

   Likewise, you should configure an appropriate ``SESAME_MAX_AGE``,
   probably a few days.

   Since emails may be forwarded, authenticated links shouldn't log the user
   in. They should only allow access to specific views.

3. Sharing links, which are a variant of authenticated links. When a user shares
   content with a guest, you may create a phantom account for the guest and
   generate an authenticated link tied to that account or you may reuse the
   user's account.

   Email forwarding is also likely in this context. Make sure that sharing links
   don't log the user in.

4. Authentication of WebSocket connections. The web application gets a token
   generated by the Django server and sends it over the WebSocket connection.
   The WebSocket server authenticate the connection with the token.

   Here's an `example with the websockets library`__.

   __ https://websockets.readthedocs.io/en/stable/howto/django.html

5. Non-critical private websites, for example for a family or club site,
   where users don't expect to manage a personal account with a password.
   Authorized users can bookmark personalized authenticated URLs.

   Here you can rely on the default settings because that's the original —
   admittedly, niche — use case for which django-sesame was built.

(In)security
------------

The major security weakness in django-sesame is a direct consequence of the
feature it implements: **whoever obtains an authentication token is able to
authenticate to your website.**

URLs end up in countless insecure places: emails, referer headers, proxy logs,
browser history, etc. You can't avoid that. At best you can mitigate it by
creating short-lived or single-use tokens.

Otherwise, a reasonable attempt was made to provide a secure solution. Tokens
are secured with modern cryptography. There are configurable options for token
invalidation.