text:
<androidx.drawerlayout.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/drawer"
    android:background="@drawable/background_color"
    tools:context=".activity.MainActivity">

    <FrameLayout
        android:id="@+id/main_frame"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

    <ListView
        android:id="@+id/drawer_list"
        android:layout_width="300dp"
        android:layout_height="match_parent"
        android:divider="@color/white"
        android:dividerHeight="0.2sp"
        android:entries="@array/drawer_items"
        android:layout_gravity="start"
        android:background="@drawable/background_color"/>

    <androidx.viewpager.widget.ViewPager
        android:id="@+id/view_pager"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="1"/>
</androidx.drawerlayout.widget.DrawerLayout>


text:
"""Unit tests for dependency_analysis.serialization."""

import unittest.mock

import class_dependency
import class_json_consts
import graph
import json_consts
import package_dependency
import package_json_consts
import serialization

class TestSerialization(unittest.TestCase):
    """Unit tests for various de/serialization functions."""
    CLASS_1 = 'p1.c1'
    CLASS_2 = 'p1.c2'
    CLASS_3 = 'p2.c3'
    BUILD_TARGET_1 = '//build/target:one'
    BUILD_TARGET_2 = '//build/target:two'
    CLASS_1_NESTED_1 = 'abc'
    CLASS_1_NESTED_2 = 'def'
    CLASS_2_NESTED_1 = 'ghi'

    # The lists in the following JSON are sorted,
    # since we sort lists when serializing (for easier testing).
    JSON_CLASS_GRAPH = {
        json_consts.NODES: [
            {
                json_consts.NAME: CLASS_1,
                json_consts.META: {
                    class_json_consts.PACKAGE:
                    'p1',
                    class_json_consts.CLASS:
                    'c1',
                    class_json_consts.BUILD_TARGETS: [BUILD_TARGET_1],
                    class_json_consts.NESTED_CLASSES:
                    [CLASS_1_NESTED_1, CLASS_1_NESTED_2],
                },
            },
            {
                json_consts.NAME: CLASS_2,
                json_consts.META: {
                    class_json_consts.PACKAGE: 'p1',
                    class_json_consts.CLASS: 'c2',
                    class_json_consts.BUILD_TARGETS: [],
                    class_json_consts.NESTED_CLASSES: [CLASS_2_NESTED_1],
                },
            },
            {
                json_consts.NAME: CLASS_3,
                json_consts.META: {
                    class_json_consts.PACKAGE:
                    'p2',
                    class_json_consts.CLASS:
                    'c3',
                    class_json_consts.BUILD_TARGETS:
                    [BUILD_TARGET_1, BUILD_TARGET_2],
                    class_json_consts.NESTED_CLASSES: [],
                },
            },
        ],
        json_consts.EDGES: [
            {
                json_consts.BEGIN: CLASS_1,
                json_consts.END: CLASS_2,
            },
            {
                json_consts.BEGIN: CLASS_1,
                json_consts.END: CLASS_3,
            },
            {
                json_consts.BEGIN: CLASS_2,
                json_consts.END: CLASS_3,
            },
        ],
    }

    JSON_PACKAGE_GRAPH = {
        json_consts.NODES: [
            {
                json_consts.NAME: 'p1',
                json_consts.META: {
                    package_json_consts.CLASSES: [CLASS_1, CLASS_2],
                },
            },
            {
                json_consts.NAME: 'p2',
                json_consts.META: {
                    package_json_consts.CLASSES: [CLASS_3],
                },
            },
        ],
        json_consts.EDGES: [
            {
                json_consts.BEGIN: 'p1',
                json_consts.END: 'p1',
                json_consts.META: {
                    package_json_consts.CLASS_EDGES: [
                        [CLASS_1, CLASS_2],
                    ],
                },
            },
            {
                json_consts.BEGIN: 'p1',
                json_consts.END: 'p2',
                json_consts.META: {
                    package_json_consts.CLASS_EDGES: [
                        [CLASS_1, CLASS_3],
                        [CLASS_2, CLASS_3],
                    ],
                },
            },
        ],
    }

    def test_class_serialization(self):
        """Tests JSON serialization of a class dependency graph."""
        test_graph = class_dependency.JavaClassDependencyGraph()
        test_graph.add_edge_if_new(self.CLASS_1, self.CLASS_2)
        test_graph.add_edge_if_new(self.CLASS_1, self.CLASS_3)
        test_graph.add_edge_if_new(self.CLASS_2, self.CLASS_3)
        test_graph.get_node_by_key(self.CLASS_1).add_nested_class(
            self.CLASS_1_NESTED_1)
        test_graph.get_node_by_key(self.CLASS_1).add_nested_class(
            self.CLASS_1_NESTED_2)
        test_graph.get_node_by_key(self.CLASS_2).add_nested_class(
            self.CLASS_2_NESTED_1)
        test_graph.get_node_by_key(self.CLASS_1).add_build_target(
            self.BUILD_TARGET_1)
        test_graph.get_node_by_key(self.CLASS_3).add_build_target(
            self.BUILD_TARGET_1)
        test_graph.get_node_by_key(self.CLASS_3).add_build_target(
            self.BUILD_TARGET_2)

        test_json_obj = serialization.create_json_obj_from_graph(test_graph)

        self.assertEqual(test_json_obj, self.JSON_CLASS_GRAPH)

    def test_package_serialization(self):
        """Tests JSON serialization of a package dependency graph."""
        class_graph = class_dependency.JavaClassDependencyGraph()
        class_graph.add_edge_if_new(self.CLASS_1, self.CLASS_2)
        class_graph.add_edge_if_new(self.CLASS_1, self.CLASS_3)
        class_graph.add_edge_if_new(self.CLASS_2, self.CLASS_3)
        class_graph.get_node_by_key(self.CLASS_1).add_nested_class(
            self.CLASS_1_NESTED_1)
        class_graph.get_node_by_key(self.CLASS_1).add_nested_class(
            self.CLASS_1_NESTED_2)
        class_graph.get_node_by_key(self.CLASS_2).add_nested_class(
            self.CLASS_2_NESTED_1)

        package_graph = package_dependency.JavaPackageDependencyGraph(
            class_graph)
        test_json_obj = serialization.create_json_obj_from_graph(package_graph)

        self.assertEqual(test_json_obj, self.JSON_PACKAGE_GRAPH)

    def test_class_deserialization(self):
        """Tests JSON deserialization of a class dependency graph.

        Since we only ever construct package graphs from class graphs
        (and that feature is tested elsewhere), we do not need to test
        deserialization of package dependency graphs as well.
        """
        test_graph = serialization.create_class_graph_from_json_obj(
            self.JSON_CLASS_GRAPH)

        node_1 = test_graph.get_node_by_key(self.CLASS_1)
        node_2 = test_graph.get_node_by_key(self.CLASS_2)
        node_3 = test_graph.get_node_by_key(self.CLASS_3)

        self.assertIsNotNone(node_1)
        self.assertIsNotNone(node_2)
        self.assertIsNotNone(node_3)
        self.assertEqual(node_1.nested_classes,
                         {self.CLASS_1_NESTED_1, self.CLASS_1_NESTED_2})
        self.assertEqual(node_2.nested_classes, {self.CLASS_2_NESTED_1})
        self.assertEqual(node_3.nested_classes, set())
        self.assertEqual(node_1.build_targets, {self.BUILD_TARGET_1})
        self.assertEqual(node_2.build_targets, set())
        self.assertEqual(node_3.build_targets,
                         {self.BUILD_TARGET_1, self.BUILD_TARGET_2})
        self.assertEqual(
            graph.sorted_edges_by_name(test_graph.edges),
            graph.sorted_edges_by_name([(node_1, node_2), (node_1, node_3),
                                        (node_2, node_3)]))

if __name__ == '__main__':
    unittest.main()

redpajama_set_name: RedPajamaGithub


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

using System.Linq;
using System.Reflection;
using Microsoft.Extensions.Logging;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
using NakedObjects.Reflector.Facet;

namespace NakedObjects.Reflector.Test.Facet;

[TestClass]
public class ActionInvocationFacetViaMethodTest {
    #region Setup/Teardown

    [TestInitialize]
    public void SetUp() { }

    #endregion

    private static void DelegateActionTest(MethodInfo method) {
        var facet = new ActionInvocationFacetViaMethod(method, null, null, null, false, null);
        var parms = method.GetParameters().Select(p => "astring").Cast<object>().ToArray();
        Assert.IsNotNull(facet.GetMethodDelegate(), method.Name);
        var testObject = new TestDelegateClass();
        facet.GetMethodDelegate().Invoke(testObject, parms);
        Assert.AreEqual(method.Name, testObject.ActionCalled);
    }

    private static void DelegateFuncTest(MethodInfo method) {
        var facet = new ActionInvocationFacetViaMethod(method, null, null, null, false, null);
        Assert.IsNotNull(facet.GetMethodDelegate(), method.Name);
        var parms = method.GetParameters().Select(p => "astring").Cast<object>().ToArray();
        Assert.AreEqual(method.Name, facet.GetMethodDelegate().Invoke(new TestDelegateClass(), parms));
    }

    private static void InvokeActionTest(MethodInfo method) {
        var facet = new ActionInvocationFacetViaMethod(method, null, null, null, false, new Mock<ILogger<ActionInvocationFacetViaMethod>>().Object);
        Assert.IsNull(facet.GetMethodDelegate());
        var parms = method.GetParameters().Select(p => "astring").Cast<object>().ToArray();
        Assert.IsNotNull(facet.GetMethod());
        var testObject = new TestDelegateClass();
        facet.GetMethod().Invoke(testObject, parms);
        Assert.AreEqual(method.Name, testObject.ActionCalled);
    }

    private static void InvokeFuncTest(MethodInfo method) {
        var facet = new ActionInvocationFacetViaMethod(method, null, null, null, false, new Mock<ILogger<ActionInvocationFacetViaMethod>>().Object);
        Assert.IsNull(facet.GetMethodDelegate());
        Assert.IsNotNull(facet.GetMethod());
        var parms = method.GetParameters().Select(p => "astring").Cast<object>().ToArray();
        Assert.AreEqual(method.Name, facet.GetMethod().Invoke(new TestDelegateClass(), parms));
    }

    [TestMethod]
    public void TestDelegateCreation() {
        DelegateActionTest(typeof(TestDelegateClass).GetMethod("Action0"));
        DelegateActionTest(typeof(TestDelegateClass).GetMethod("Action1"));
        DelegateActionTest(typeof(TestDelegateClass).GetMethod("Action2"));
        DelegateActionTest(typeof(TestDelegateClass).GetMethod("Action3"));
        DelegateActionTest(typeof(TestDelegateClass).GetMethod("Action4"));
        DelegateActionTest(typeof(TestDelegateClass).GetMethod("Action5"));
        DelegateActionTest(typeof(TestDelegateClass).GetMethod("Action6"));

        DelegateFuncTest(typeof(TestDelegateClass).GetMethod("Func0"));
        DelegateFuncTest(typeof(TestDelegateClass).GetMethod("Func1"));
        DelegateFuncTest(typeof(TestDelegateClass).GetMethod("Func2"));
        DelegateFuncTest(typeof(TestDelegateClass).GetMethod("Func3"));
        DelegateFuncTest(typeof(TestDelegateClass).GetMethod("Func4"));
        DelegateFuncTest(typeof(TestDelegateClass).GetMethod("Func5"));
        DelegateFuncTest(typeof(TestDelegateClass).GetMethod("Func6"));
    }

    [TestMethod]
    public void TestDelegateNonCreation() {
        InvokeActionTest(typeof(TestDelegateClass).GetMethod("Action7"));
        InvokeFuncTest(typeof(TestDelegateClass).GetMethod("Func7"));
    }

    #region Nested type: TestDelegateClass

    // ReSharper disable UnusedMember.Global
    public class TestDelegateClass {
        public string ActionCalled { get; set; }

        public void Action0() {
            ActionCalled = "Action0";
        }

        public void Action1(string p1) {
            ActionCalled = "Action1";
        }

        public void Action2(string p1, string p2) {
            ActionCalled = "Action2";
        }

        public void Action3(string p1, string p2, string p3) {
            ActionCalled = "Action3";
        }

        public void Action4(string p1, string p2, string p3, string p4) {
            ActionCalled = "Action4";
        }

        public void Action5(string p1, string p2, string p3, string p4, string p5) {
            ActionCalled = "Action5";
        }

        public void Action6(string p1, string p2, string p3, string p4, string p5, string p6) {
            ActionCalled = "Action6";
        }

        public void Action7(string p1, string p2, string p3, string p4, string p5, string p6, string p7) {
            ActionCalled = "Action7";
        }

        public string Func0() => "Func0";

        public string Func1(string p1) => "Func1";

        public string Func2(string p1, string p2) => "Func2";

        public string Func3(string p1, string p2, string p3) => "Func3";

        public string Func4(string p1, string p2, string p3, string p4) => "Func4";

        public string Func5(string p1, string p2, string p3, string p4, string p5) => "Func5";

        public string Func6(string p1, string p2, string p3, string p4, string p5, string p6) => "Func6";

        public string Func7(string p1, string p2, string p3, string p4, string p5, string p6, string p7) => "Func7";
    }
    // ReSharper restore UnusedMember.Global

    #endregion
}


text:
        <button type="button" class="close" ng-click="vm.cancel()" data-dismiss="modal">
            ×
        </button>

{{vm.entity.descripcion}}

        <form name="periodoForm" class="form-in-line"
            ng-submit="vm.savePeriodo(periodoForm, vm.entity)" role="form">

                    Descripción:
                    <input name = "descripcion" type="text" ng-model= "vm.entity.descripcion"
                        class="form-control input-sm" id="descripcion" placeholder="descripcion"
                        style="width:100%" required="required">

                    Año:
                    <input name = "anno" type="text" ng-model= "vm.entity.anno"
                        class="form-control input-sm" id="anno" placeholder="Año"
                        style="width:100%" required="required">

                    Mes:
                    <input name = "mes" type="text" ng-model= "vm.entity.mes"
                        class="form-control input-sm" id="mes" placeholder="Mes"
                        style="width:100%" required="required">

                    Periodo:
                    <input name = "periodo" type="text" ng-model= "vm.entity.periodo"
                        class="form-control input-sm" id="periodo" placeholder="Periodo"
                        style="width:100%" required="required">

                    Desde:
                    <input name = "desde" type="date"
                        ng-model= "vm.entity.desde"
                        class="form-control input-sm" id="desde"  style="width:100%">

                    Hasta:
                    <input name = "hasta" type="date"
                        ng-model= "vm.entity.hasta"
                        class="form-control input-sm" id="hasta"  style="width:100%">

                    Estado:
                    <select ng-model="vm.entity.estado" name="estado"
                        required="required" class="input-sm form-control">
                        <option value="Activo">Activo</option>
                        <option value="Liquidado">Liquidado</option>
                        <option value="Pendiente">Pendiente</option>
                        <option value="Revision">Revision</option>
                    </select>

                <button type="submit" class="btn btn-success"
                    ng-disabled="periodoForm.$invalid || !periodoForm.$dirty">
                    Actualizar
                </button>
                <button type="button" class="btn btn-success"
                    ng-if="vm.entity.id && !periodoForm.$dirty"
                    ng-click="vm.borrarRegistro()">
                    Borrar
                </button>

        </form>

        <button type="button" class="btn btn-default" ng-click="vm.cancel()" data-dismiss="modal">
            Cancelar
        </button>


text:
package com.tale.ext;

import com.blade.jdbc.model.Paginator;
import com.blade.kit.*;
import com.tale.controller.BaseController;
import com.tale.init.TaleConst;
import com.tale.service.SiteService;
import com.tale.utils.TaleUtils;
import com.vdurmont.emoji.EmojiParser;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 公共函数
 * <p>
 * Created by biezhi on 2017/2/21.
 */
public final class Commons {

    private static SiteService siteService;

    private static final List EMPTY = new ArrayList(0);

    private static final Random rand = new Random();

    private static final String TEMPLATES = "/templates/";

    public static void setSiteService(SiteService ss) {
        siteService = ss;
        Theme.setSiteService(ss);
    }

    /**
     * 判断分页中是否有数据
     *
     * @param paginator
     * @return
     */
    public static boolean is_empty(Paginator paginator) {
        return null == paginator || CollectionKit.isEmpty(paginator.getList());
    }

    /**
     * 返回网站首页链接,如:http://tale.biezhi.me
     *
     * @return
     */
    public static String site_url() {
        return site_url("");
    }

    /**
     * 返回当前主题名称
     *
     * @return
     */
    public static String site_theme() {
        return site_option("site_theme", "default");
    }

    /**
     * 返回网站链接下的全址
     *
     * @param sub 后面追加的地址
     * @return
     */
    public static String site_url(String sub) {
        return site_option("site_url") + sub;
    }

    /**
     * 网站标题
     *
     * @return
     */
    public static String site_title() {
        return site_option("site_title");
    }

    /**
     * 网站配置项
     *
     * @param key
     * @return
     */
    public static String site_option(String key) {
        return site_option(key, "");
    }

    /**
     * 网站配置项
     *
     * @param key
     * @param defalutValue 默认值
     * @return
     */
    public static String site_option(String key, String defalutValue) {
        if (StringKit.isBlank(key)) {
            return "";
        }
        return TaleConst.OPTIONS.get(key, defalutValue);
    }

    /**
     * 返回站点设置的描述信息
     * @return
     */
    public static String site_description(){
        return site_option("site_description");
    }

    /**
     * 截取字符串
     *
     * @param str
     * @param len
     * @return
     */
    public static String substr(String str, int len) {
        if (str.length() > len) {
            return str.substring(0, len);
        }
        return str;
    }

    /**
     * 返回主题URL
     *
     * @return
     */
    public static String theme_url() {
        return Commons.site_url(TEMPLATES + BaseController.THEME);
    }

    /**
     * 返回主题下的文件路径
     *
     * @param sub
     * @return
     */
    public static String theme_url(String sub) {
        return Commons.site_url(TEMPLATES + BaseController.THEME + sub);
    }

    /**
     * 返回gravatar头像地址
     *
     * @param email
     * @return
     */
    public static String gravatar(String email) {
        String avatarUrl = "https://secure.gravatar.com/avatar";
        if (StringKit.isBlank(email)) {
            return avatarUrl;
        }
        String hash = Tools.md5(email.trim().toLowerCase());
        return avatarUrl + "/" + hash;
    }

    /**
     * 格式化unix时间戳为日期
     *
     * @param unixTime
     * @return
     */
    public static String fmtdate(Integer unixTime) {
        return fmtdate(unixTime, "yyyy-MM-dd");
    }

    /**
     * 格式化日期
     * @param date
     * @param fmt
     * @return
     */
    public static String fmtdate(Date date, String fmt) {
        return DateKit.dateFormat(date, fmt);
    }

    /**
     * 格式化unix时间戳为日期
     *
     * @param unixTime
     * @param patten
     * @return
     */
    public static String fmtdate(Integer unixTime, String patten) {
        if (null != unixTime && StringKit.isNotBlank(patten)) {
            return DateKit.formatDateByUnixTime(unixTime, patten);
        }
        return "";
    }

    /**
     * 获取随机数
     * @param max
     * @param str
     * @return
     */
    public static String random(int max, String str){
        return UUID.random(1, max) + str;
    }

    /**
     * An :grinning:awesome :smiley:string 😄with a few :wink:emojis!
     *
     * 这种格式的字符转换为emoji表情
     *
     * @param value
     * @return
     */
    public static String emoji(String value){
        return EmojiParser.parseToUnicode(value);
    }

    /**
     * 获取文章第一张图片
     *
     * @return
     */
    public static String show_thumb(String content) {
        content = TaleUtils.mdToHtml(content);
        if (content.contains("<img")) {
            String img = "";
            String regEx_img = "<img.*src\\s*=\\s*(.*?)[^>]*?>";
            Pattern p_image = Pattern.compile(regEx_img, Pattern.CASE_INSENSITIVE);
            Matcher m_image = p_image.matcher(content);
            if (m_image.find()) {
                img = img + "," + m_image.group();
                // //匹配src
                Matcher m = Pattern.compile("src\\s*=\\s*\'?\"?(.*?)(\'|\"|>|\\s+)").matcher(img);
                if (m.find()) {
                    return m.group(1);
                }
            }
        }
        return "";
    }

}


text:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
                                                   xmlns:app="http://schemas.android.com/apk/res-auto"
                                                   xmlns:tools="http://schemas.android.com/tools"
                                                   android:layout_width="match_parent"
                                                   android:layout_height="match_parent"
                                                   tools:context=".fragments.SettingsFragment"
                                                   android:id="@+id/st_layout">

    <androidx.recyclerview.widget.RecyclerView
            android:layout_width="0dp"
            android:layout_height="0dp"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            android:layout_marginTop="@dimen/st_horizontal_margin"
            android:layout_marginBottom="@dimen/st_horizontal_margin"
            app:layout_constraintTop_toTopOf="parent"
            app:layout_constraintBottom_toBottomOf="parent" android:id="@+id/st_recycler"/>
</androidx.constraintlayout.widget.ConstraintLayout>


text:
/**
 * @file   idregister.h
 * @author Jan Mussler
 * @brief Defintion of IdRegister class
 *
 * This class is used to store associations between IDs and Descriptors
 */

#ifndef IDREGISTER_H
#define	IDREGISTER_H

#include <string>
#include <map>

namespace gi {
    namespace instrumenter {
        typedef unsigned int ContextIDType;

        class IdRegister {
        public:

            enum IdType {
                FUNCTION, LOOP, CALLSITE
            };

            /**
             * There is only one ID Store, use get() to access it
             *
             * @return Instance
             */
            static IdRegister& get();

            void enable();
            void disable();
            bool isEnabled();

            /**
             * Add a new ID with its type and name of the object
             *
             * @param t type that is associated with id: function, loop, or callsite
             * @param id the ID itself
             * @param value name of associated object
             */
            void addId(IdType t, ContextIDType id, std::string name);

            /**
             *
             * @param t type for the IDs returned in the list
             * @param sepIdIdent how to seperate id from associated name ( default = )
             * @param sepEntries how to seperate two ids ( default = \n )
             * @return a string with the list of ids and names
             */
            std::string getList(IdType t,std::string sepIdIdent = "=", std::string sepEntries = "\n");

        private:
            /* singleton pattern, use get() to ::get() instance*/
            static IdRegister* reg;

            /**
             * Is logging of IDs enabled?
             * @var enabled
             */
            bool enabled;

            /**
             * container for all types and used IDs with the associated object's name
             * @var store
             */
            std::map<IdType, std::map<ContextIDType, std::string> > store;

            IdRegister();
        };
    }
}
#endif	/* IDREGISTER_H */


text:
using Ploeh.AutoFixture;
using Ploeh.AutoFixture.AutoNSubstitute;
using Ploeh.AutoFixture.Xunit2;

namespace Simple.Xml.Structure.UnitTests
{
    public class AutoSubstituteData : AutoDataAttribute
    {
        public AutoSubstituteData() : base(new Fixture().Customize(new AutoNSubstituteCustomization()))
        {

        }
    }
}


text:
<!DOCTYPE html>

<title>OffscreenCanvas test: 2d.shadow.enable.off.1</title>

2d.shadow.enable.off.1

Shadows are not drawn when only shadowColor is set


text:
cd "$(dirname "$0")"

# CLI, app, and test module temporary locations
# http://unix.stackexchange.com/a/84980
temp_app_path=`mktemp -d 2>/dev/null || mktemp -d -t 'temp_app_path'`

# Load functions for working with local NPM registry (Verdaccio)
source local-registry.sh

function cleanup {
  echo 'Cleaning up.'
  ps -ef | grep 'react-scripts' | grep -v grep | awk '{print $2}' | xargs kill -9
  cd "$root_path"
  # Restore the original NPM and Yarn registry URLs and stop Verdaccio
  stopLocalRegistry
}

# Error messages are redirected to stderr
function handle_error {
  echo "$(basename $0): ERROR! An error was encountered executing line $1." 1>&2;
  cleanup
  echo 'Exiting with error.' 1>&2;
  exit 1
}

function handle_exit {
  cleanup
  echo 'Exiting without error.' 1>&2;
  exit
}

# Check for the existence of one or more files.
function exists {
  for f in $*; do
    test -e "$f"
  done
}

# Exit the script with a helpful error message when any error is encountered
trap 'set +x; handle_error $LINENO $BASH_COMMAND' ERR

# Cleanup before exit on any termination signal
trap 'set +x; handle_exit' SIGQUIT SIGTERM SIGINT SIGKILL SIGHUP

# Echo every command being executed
set -x

# Go to root
cd ..
root_path=$PWD

if hash npm 2>/dev/null
then
  npm i -g npm@latest
fi

# Bootstrap monorepo
yarn

# ******************************************************************************
# First, publish the monorepo.
# ******************************************************************************

# Start the local NPM registry
startLocalRegistry "$root_path"/tasks/verdaccio.yaml

# Publish the monorepo
publishToLocalRegistry

# ******************************************************************************
# Now that we have published them, run all tests as if they were released.
# ******************************************************************************

# Run all tests
cd test/
CI=true ../node_modules/.bin/jest -w 2

# Cleanup
cleanup


text:
require "minitest/autorun"
require "webmock/minitest"

require "helper"
require_relative "../lib/poeditor"

class Test < Minitest::Test

  def stub_api(request_action, request_body_include=nil, response_body)
    request_body_include = request_body_include || {}
    stub_request(:post, "https://api.poeditor.com/v2/#{request_action}")
      .with(:body => hash_including(request_body_include))
      .to_return(:body => response_body)
  end

  def stub_api_export(language, body)
    stub_api "projects/export", {"language" => language}, <<~BODY
      {
        "response": {
          "status": "success",
          "code": "200",
          "message": "OK"
        },
        "result": {
          "url": "https://poeditor.com/api/download/file/#{language}"
        }
      }
    BODY
    stub_request(:get, "https://poeditor.com/api/download/file/#{language}")
      .to_return(body: body)
  end

  def stub_api_export_failure
    stub_api "export", <<~BODY
      {
        "response": {
          "status": "fail",
          "code": "4011",
          "message": "Invalid API Token"
        }
      }
    BODY
  end

end


text:
import * as workingDir from "../../disk/workingDir";
import * as fsu from "../../utils/fsu";

export function createEditorconfig(data:{}): Promise<{alreadyPresent: string}> {
    const defaultContents = `
[*.{js,jsx,ts,tsx}]
indent_style = space
indent_size = 2
trim_trailing_whitespace = true
insert_final_newline = true

[*.md]
trim_trailing_whitespace = true
insert_final_newline = true
    `.trim();
    const filePath = workingDir.makeAbsolute('./.editorconfig');

    if (fsu.existsSync(filePath)){
        return Promise.resolve({alreadyPresent:filePath});
    }
    fsu.writeFile(filePath,defaultContents);
    return Promise.resolve({alreadyPresent:''});
}


text:
module IuguSDK
  module Controllers
    module Helpers
      extend ActiveSupport::Concern

      def search_user_account( account_id )
        return false unless signed_in? and current_user
        current_user.account_users.where( :account_id => account_id ).try(:first)
      end

      def current_user_account
        @current_user_account ||= search_user_account( session[:current_account_id] )
      end

      def current_account
        current_user_account.try(:account)
      end

      def set_account( resource, account_id=nil )
        if account_id == nil
          account_id = cookies[:last_used_account_id] if cookies[:last_used_account_id]
        end
        selected_account = resource.default_account( account_id )
        if selected_account
          cookies[:last_used_account_id] = { :value => selected_account.id, :expires => 365.days.from_now }
          session[ :current_account_id ] = selected_account.id
        end
        selected_account
      end

      def is_active?(control, action="", id="")
        if id == ""
          if action == ""
            return true if controller_name == control.gsub("/", "")
          else
            return true if controller_name == control.gsub("/", "") && action_name == action
          end
        else
          return true if controller_name == control.gsub("/", "") && action_name == action && id == params[:id]
        end
        return false
      end

      def body_classes
        [controller_name,action_name,'page-' + controller_name + '-' + action_name]
      end
    end
  end
end


text:
package it.prisma.businesslayer.bizlib.rest.apiclients.iaas.openstack;

import it.prisma.domain.dsl.iaas.openstack.ErrorWrapperCompute;
import it.prisma.utils.web.ws.rest.apiencoding.NoMappingModelFoundException;
import it.prisma.utils.web.ws.rest.apiencoding.RestMessage;
import it.prisma.utils.web.ws.rest.apiencoding.ServerErrorResponseException;
import it.prisma.utils.web.ws.rest.apiencoding.decode.RestResponseDecodeStrategy;

import javax.ws.rs.core.Response.Status;
import javax.ws.rs.core.Response.StatusType;

import org.javatuples.Pair;

import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * Generic Rest Decode strategy for the Openstack 'protocol'.
 *
 * @author l.biava
 *
 */
public class OpenstackComputeRRDStrategy<APIResponseType> implements
		RestResponseDecodeStrategy {

	private Class<APIResponseType> targetClass;

	public OpenstackComputeRRDStrategy(Class<APIResponseType> c) {
		targetClass = c;
	}

	@Override
	public JavaType getModelClass(RestMessage msg)
			throws NoMappingModelFoundException, ServerErrorResponseException {
		Pair<StatusType, JavaType> result = strategy(msg);
		return result.getValue1();
	}

	@Override
	public StatusType getStatus(RestMessage msg)
			throws NoMappingModelFoundException, ServerErrorResponseException {
		Pair<StatusType, JavaType> result = strategy(msg);
		return result.getValue0();
	}

	private Pair<StatusType, JavaType> strategy(RestMessage msg)
			throws NoMappingModelFoundException, ServerErrorResponseException {
		StatusType status = Status.OK;
		JavaType clazz;
		ObjectMapper mapper = new ObjectMapper();

		int httpStatusCode = msg.getHttpStatusCode();

		if (httpStatusCode >= 200 && httpStatusCode < 300 ) {
			// Response class type
			clazz = mapper.getTypeFactory().constructType(targetClass);

		} else if (httpStatusCode >= 400) {
			status = Status.INTERNAL_SERVER_ERROR;
			clazz = mapper.getTypeFactory()
					.constructType(ErrorWrapperCompute.class);
		} else {
			throw new ServerErrorResponseException("SERVER_ERROR_RESPONSE",
					null, msg, httpStatusCode);
		}

		return new Pair<StatusType, JavaType>(status, clazz);
	}

}


text:
class HTMLUploader < CarrierWave::Uploader::Base

  # Include RMagick or ImageScience support:
  # include CarrierWave::RMagick
  # include CarrierWave::ImageScience

  # Choose what kind of storage to use for this uploader:
  storage :file
  # storage :s3

  # Override the directory where uploaded files will be stored.
  # This is a sensible default for uploaders that are meant to be mounted:
  def store_dir
    "bucket/#{mounted_as}"
  end

  # Provide a default URL as a default if there hasn't been a file uploaded:
  # def default_url
  #   "/images/fallback/" + [version_name, "default.png"].compact.join('_')
  # end
  #
  # def scale(width, height)
  #   # do something
  # end

  # Create different versions of your uploaded files:
  # version :thumb do
  #   process :scale => [50, 50]
  # end

  # Add a white list of extensions which are allowed to be uploaded.
  # For images you might use something like this:
  # def extension_white_list
  #   %w(jpg jpeg gif png)
  # end

  # Override the filename of the uploaded files:
  def filename
    "#{model.url_hash}"
  end

end


text:
package io.katharsis.core.internal.dispatcher.controller;

import java.io.Serializable;
import java.util.LinkedList;
import java.util.List;

import io.katharsis.core.internal.repository.adapter.RelationshipRepositoryAdapter;
import io.katharsis.core.internal.utils.parser.TypeParser;
import io.katharsis.repository.request.HttpMethod;
import io.katharsis.repository.request.QueryAdapter;
import io.katharsis.resource.ResourceIdentifier;
import io.katharsis.resource.information.ResourceField;
import io.katharsis.resource.registry.ResourceRegistry;

public class RelationshipsResourcePost extends RelationshipsResourceUpsert {

	public RelationshipsResourcePost(ResourceRegistry resourceRegistry, TypeParser typeParser) {
		super(resourceRegistry, typeParser);
	}

	@Override
	public HttpMethod method() {
		return HttpMethod.POST;
	}

	@Override
	public void processToManyRelationship(Object resource, Class<? extends Serializable> relationshipIdType, ResourceField resourceField, Iterable<ResourceIdentifier> dataBodies, QueryAdapter queryAdapter,
			RelationshipRepositoryAdapter relationshipRepositoryForClass) {
		List<Serializable> parsedIds = new LinkedList<>();

		for (ResourceIdentifier dataBody : dataBodies) {
			Serializable parsedId = typeParser.parse(dataBody.getId(), relationshipIdType);
			parsedIds.add(parsedId);
		}

		// noinspection unchecked
		relationshipRepositoryForClass.addRelations(resource, parsedIds, resourceField, queryAdapter);
	}

	@Override
	protected void processToOneRelationship(Object resource, Class<? extends Serializable> relationshipIdType, ResourceField resourceField, ResourceIdentifier dataBody, QueryAdapter queryAdapter,
			RelationshipRepositoryAdapter relationshipRepositoryForClass) {
		Serializable parsedId = null;
		if (dataBody != null) {
			parsedId = typeParser.parse(dataBody.getId(), relationshipIdType);
		}
		// noinspection unchecked
		relationshipRepositoryForClass.setRelation(resource, parsedId, resourceField, queryAdapter);
	}
}


text:
package alice.tuprolog;

import java.util.*;

/**
 * This class represents a prolog Flag
 */
class Flag implements java.io.Serializable {

        private static final long serialVersionUID = 1L;
        private String name;
        private Struct valueList;
        private Term value;
        private Term defaultValue;
        private boolean modifiable;
        private String libraryName;

        /**
         * Builds a Prolog flag
         *
         * @param name is the name of the flag
         * @param valueSet is the Prolog list of the possible values
         * @param defValue is the default value
         * @param modifiable states if the flag is modifiable
         * @param library is the library defining the flag
         */
        public Flag(String name, Struct valueSet, Term defValue, boolean modifiable, String library) {
                this.name = name;
                this.valueList = valueSet;
                defaultValue = defValue;
                this.modifiable = modifiable;
                libraryName = library;
                value = defValue;
        }

        protected Flag() {
        }

        /**
         * Gets a deep copy of the flag
         *
         * @return a copy of the flag
         */
        @Override
        public Object clone() {
                Flag f = new Flag();
                f.name = name;
                f.valueList = (Struct) valueList.copy(new HashMap<>(), Var.ORIGINAL);
                f.value = value.copy(new HashMap<>(), Var.ORIGINAL);
                f.defaultValue = defaultValue.copy(new HashMap<>(), Var.ORIGINAL);
                f.modifiable = modifiable;
                f.libraryName = libraryName;
                return f;
        }

        /**
         * Checks if a value is valid according to flag description
         *
         * @param value the possible value of the flag
         * @return flag validity
         */
        public boolean isValidValue(Term value) {
                java.util.Iterator<? extends Term> it = valueList.listIterator();
                while (it.hasNext()) {
                        Term t = (Term) it.next();
                        if (value.match(t)) {
                                return true;
                        }
                }
                return false;
        }

        /**
         * Gets the name of the flag
         *
         * @return the name
         */
        public String getName() {
                return name;
        }

        /**
         * Gets the list of flag possible values
         *
         * @return a Prolog list
         */
        public Struct getValueList() {
                return valueList;
        }

        /**
         * Sets the value of a flag
         *
         * @param value new value of the flag
         * @return true if the value is valid
         */
        public boolean setValue(Term value) {
                if (isValidValue(value) && modifiable) {
                        this.value = value;
                        return true;
                } else {
                        return false;
                }
        }

        /**
         * Gets the current value of the flag
         *
         * @return flag current value
         */
        public Term getValue() {
                return value;
        }

        /**
         * Checks if the value is modifiable
         *
         * @return
         */
        public boolean isModifiable() {
                return modifiable;
        }

        /**
         * Gets the name of the library where the flag has been defined
         *
         * @return the library name
         */
        public String getLibraryName() {
                return libraryName;
        }

}


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

namespace designPatterns.Domain.DesignPattern.BridgePattern
{
    public interface IVideoSource
    {
        string GetTvGuide();
        string PlayVideo();
    }
}


text:
class TestPyxnatSession:
    def __init__(self, project, subject, session, scans, assessors):
        self.scans_ = scans
        self.assessors_ = assessors
        self.project = project
        self.subject = subject
        self.session = session

    def scans(self):
        return self.scans_

    def assessors(self):
        return self.assessors_

class TestAttrs:
    def __init__(self, properties):
        pass

class TestPyxnatScan:
    def __init__(self, project, subject, session, scanjson):
        self.scanjson = scanjson
        self.project = project
        self.subject = subject
        self.session = session
        uristr = '/data/project/{}/subjects/{}/experiments/{}/scans/{}'
        self._uri = uristr.format(project,
                                  subject,
                                  session,
                                  self.scanjson['label'])

    def id(self):
        return self.scanjson['id']

    def label(self):
        return self.scanjson['label']

class TestPyxnatAssessor:
    def __init__(self, project, subject, session, asrjson):
        self.asrjson = asrjson
        self.project = project
        self.subject = subject
        self.session = session
        uristr = '/data/project/{}/subjects/{}/experiments/{}/assessors/{}'
        self._uri = uristr.format(project,
                                  subject,
                                  session,
                                  self.asrjson['label'])

    def id(self):
        return self.asrjson['id']

    def label(self):
        return self.asrjson['label']

    def inputs(self):
        return self.asrjson['xsitype'] + '/' + self.asrjson['inputs']


text:
<?php
declare(strict_types=1);

namespace ManaPHP\Http\Filter;

interface BeginFilterInterface
{
    public function onBegin(): void;
}


text:
<?php

/**
 * AccountTable
 *
 * This class has been auto-generated by the Doctrine ORM Framework
 */
class AccountTable extends Doctrine_Table
{
    /**
     * Returns an instance of this class.
     *
     * @return object AccountTable
     */
    public static function getInstance()
    {
        return Doctrine_Core::getTable('Account');
    }

    public static function getAllUserAccounts($user) {
        $accounts = Doctrine_Query::create()
            ->from('Account a')
            ->leftJoin('a.UserAccount ua')
            ->leftJoin('a.Manager m')
            ->where('ua.user_id = ?', $user->getId())
            ->andWhere('ua.is_active = ?', true)
            ->execute();

        /*$result = array();
        foreach($accounts as $account){
            $manager = self::getAccountManagers($account->getId());
            $result[$account->getId()]['title'] = $account->getTitle();
            $result[$account->getId()]['photo'] = $account->getPhoto();
            $result[$account->getId()]['manager'] = $manager;
        }*/
        //return $result;
        return $accounts;
    }

    /*public static function getAccountManagers($account_id){
        $manager = Doctrine_Manager::getInstance()->getCurrentConnection();
        $query = "SELECT u.username
FROM user_account ua
        INNER JOIN
        (
            SELECT account_id, MIN(created_at) min_date
            FROM user_account
            WHERE is_manager = 1 AND account_id = $account_id
            GROUP BY account_id
        ) ua2 ON ua.account_id = ua2.account_id AND ua.created_at = ua2.min_date
LEFT JOIN sf_guard_user u ON ua.user_id = u.id
";
        return $manager->execute($query)->fetchColumn(0);
    }*/
}


text:
import Operator from '../Operator';
import Observer from '../Observer';
import Subscriber from '../Subscriber';
import Subscription from '../Subscription';

import tryCatch from '../util/tryCatch';
import {errorObject} from '../util/errorObject';
import bindCallback from '../util/bindCallback';

export default function _finally<T>(finallySelector: () => void, thisArg?: any) {
  return this.lift(new FinallyOperator(thisArg ?
    <() => void> bindCallback(finallySelector, thisArg, 2) :
    finallySelector));
}

export class FinallyOperator<T, R> implements Operator<T, R> {

  finallySelector: () => void;

  constructor(finallySelector: () => void) {
    this.finallySelector = finallySelector;
  }

  call(observer: Observer<T>): Observer<T> {
    return new FinallySubscriber(observer, this.finallySelector);
  }
}

export class FinallySubscriber<T> extends Subscriber<T> {
  constructor(destination: Observer<T>, finallySelector: () => void) {
    super(destination);
    this.add(new Subscription(finallySelector));
  }
}


text:
class LogProvider
	: public MinCOM::CommonImpl< TrMngKit::ITextLogProvider >
{
public:

	// ITextLogProvider implementations section
	virtual result AddMessage(const StringA& type, const StringA& message, const StringA& section)
	{
		ConsoleHelpersKit::Console::EventNotify(
			StringA("Trainer. ")+
			type +
			StringA(": ")+
			message +
			StringA(" [ ")+
			section +
			StringA(" ]")
		);

		return S_OK;
	}

	// ITextLogProvider implementations section

	// ICommon implementations section
	virtual result QueryInterface(REFIID iid, void** ppObject)
	{
		if (iid == MinCOM::IID_ICommon)
			*ppObject = MinCOM::CommonImpl< TrMngKit::ITextLogProvider >::GetCommon();

		else if (iid == TrMngKit::IID_ILogProvider)
			*ppObject = static_cast< TrMngKit::ILogProvider* >(this);

		else if (iid == TrMngKit::IID_ITextLogProvider)
			*ppObject = static_cast< TrMngKit::ITextLogProvider* >(this);

		else
		{
			*ppObject = NULL;
			return E_NOINTERFACE;
		}

		MinCOM::CommonImpl< TrMngKit::ITextLogProvider >::GetCommon()->AddRef();
		return S_OK;
	}
};

#endif // !LOGPROVIDER_H__TRAINTOOL__INCLUDED_


text:
One Grid is the simplest grid system for fixed-height infinite blocks

## ⚠ Archive Notice

In 2016, I made this tiny CSS library for grid systems (less than one kilobyte), using floats and JavaScript for height calculation. With Flexbox and CSS grid, this is now redundant, so please don't use this in production.


text:
Project maintainers and mentors, please submit the ideas below (under the Proposed Project Ideas section) section using the [template](/PROJECT_IDEA_TEMPLATE.md).

### Template

```
#### CNCF Project Name
##### Title

-	Description:
-	Recommended Skills:
-	Mentor(s):
-	Upstream Issue (URL):
```

### Sample:

#### Prometheus
##### Refactor the APIs for better readability and less maintenance overhead

- Description: Currently the HTTP API is not very well organized and needs some tidying up. The actual course of action is not decided yet, but [go-kit](https://github.com/go-kit/kit) looks like a good fit.
-	Recommended Skills: golang
-	Mentor(s): Krasi Georgiev (@krasi-georgiev)
-	Issue: https://github.com/prometheus/prometheus/issues/3416

### Proposed Project ideas

### Kubernetes

#### Kubernetes working group for CSI driver

-	Description: Container Storage Interface (CSI) is a standard for exposing storage systems to containerized workloads on Kubernetes. The idea is to implement a few new CSI features and also e2e tests to cover those features, e.g. volume expansion, Windows support, inline volume support etc. Also, there are requirements to rewrite some flexvolume drivers(e.g. [smb driver](https://github.com/Azure/kubernetes-volume-drivers/tree/master/flexvolume/smb)) to CSI driver.
-	Recommended Skills: golang, Kubernetes
-	Mentor(s): Andy Zhang @andyzhangx
-	Issue:
	-	https://github.com/kubernetes-sigs/azurefile-csi-driver/issues
	-	https://github.com/Azure/kubernetes-volume-drivers/issues/48

#### Kubernetes Multi-Tenancy Working Group: Multi-Tenancy Benchmarks

-	Description: The Kubernetes Multi-Tenancy Working Group is chartered with exploring and defining multi-tenancy models for Kubernetes. An overview of working group activities can be found in this Kubernetes Multi-Tenancy Working Group . The Multitenancy Benchmarks effort focuses on measuring and validating the desired behaviors for multitenancy. Part of this effort is to automate behavioral and configuration checks on existing clusters, which will be the focus of this project. This automated test suit will help all Kubernetes users validate whether their clusters are setup correctly for multi-tenancy.
-	Recommended Skills: Go, Kubernetes
-	Mentor(s):Tasha Drew (@tashimi), Ryan Bezdicek (@rjbez17), Jim Bugwadia (@JimBugwadia)
-	Issue: https://github.com/kubernetes-sigs/multi-tenancy/issues/551

#### Kubernetes Policy Working Group: Policy Violation CRD

-   Description: The Kubernetes Policy Working Group is providing an overall architecture that describes both the current policy related implementations as well as future policy related proposals in Kubernetes. As part of this effort, the group is proposing a Kubernetes Custom Resources Definition (CRD) for policy violations and writing adapters to convert from various Kubernetes policy management tools such as OPA, Falco, Kyverno, kube-bench, etc. to report policy violations in a common format. The Policy Violation CRD can then be used by the Dashboard to show violations.
-   Recommended Skills: Go, Kubernetes
-   Mentor(s): Jim Bugwadia (@JimBugwadia)
-   Issue: https://github.com/kubernetes-sigs/wg-policy-prototypes/issues/3

### Argo

#### Kruise Deployment Wizard

-	Description: The Kruise Wizard is a tool that streamlines the creation of initial deployment manifests for complex Kubernetes applications. Development and traditional Ops teams can now use a wizard-like tool to define application deployments and generate a set of Kustomized based YAML files. These files are committed to a Git repository allowing seamless GitOps adoption. Kustomized based Kubernetes deployments can then be deployed utilizing a variety of CD tools as in our case: ArgoCD.
-	Recommended Skills: golang, kubernetes, argoCD, Kustomize
-	Mentor(s): Ken Owens (@kenowens12)
-	Upstream Issue (URL):https://github.com/Mastercard/Kruise-API

### OPA

#### OPA Go APIs

-	Description: We embed OPA in our applications to implement policy as code. We found that current OPA Go APIs are not designed for API calls. It is mainly for standalone CLI.  For example, policy input has to be file via file path. In APIs, policy input could be either string or bytes.  We have to write policy data into temp file in order to call OPA APIs.  In addition to OPA APIs, we also want to build policy repository to support policy agent
-	Recommended Skills: golang, OPA
-	Mentor(s): Jingnan Zhou (@jingnanzhou)
-	Upstream Issue (URL): https://github.com/open-policy-agent/opa/issues/2336

#### OPA - MongoDB query translator

-   Description: MongoDB is a general-purpose, document-based, distributed database with a rich query language. OPA features a high-level declarative language called `Rego` purpose-built for expressing policies over complex hierarchical data structures. OPA is often used to enforce policies over incoming API requests, but using OPA's "partial evaluation" feature it is also possible to enforce policies when data is accessed inside of document-oriented databases like MongoDB. In this model, callers query OPA to obtain a set of conditions to apply to the database query and then rewrite the database query accordingly. There are existing projects that translate "partial evaluation" results to SQL and Elasticsearch. This project would involve designing and implementing a Rego to MongoDB query translator that supports basic relational operations like ==, !=, >, <, etc. This project would hugely benefit the community to perform authorization and data-filtering in MongoDB using OPA.
-   Recommended Skills: Go/Python, MongoDB (not required, but nice to have)
-   Mentor(s): Ash Narkar (@ashutosh-narkar)
-   Issue: https://github.com/open-policy-agent/opa/issues/2059

### Thanos

#### Thanos Query Frontend

- Description: As per [proposal](https://thanos.io/proposals/202004_embedd_cortex_frontend.md/) we plan to embedd Cortex query frontend as new Thanos command. With this project you will have opportunity to work in
both Cortex and Thanos codebase to improve both worlds while creating shiny new command in Thanos project for this microservice proxy.
- Recommended Skills: go, distributed systems, caching
- Mentor(s): Bartlomiej Plotka (@bwplotka)
- Issue: https://github.com/thanos-io/thanos/issues/2454

#### Versioned Website Docs

- Description: The Thanos website includes a documentation area that contains per-component docs and configuration built by rendering the markdown files from the tip of master of the Thanos repository. This frequently causes confusion for users, as breaking changes are often merged into master that conflict with the APIs of previous releases. To solve this user-facing issue, we would like to allow the website to show a different set of docs for every Thanos release. This project will involve designing a documentation structure and version picker in the website to select different versions of documents. We will also need to design a workflow for managing docs that integrates with our Git workflow, i.e. updating corresponding docs on pull requests, cherry-picks, etc.
- Recommended Skills: go, HTML, JavaScript, CSS
- Mentor(s): Lucas Servén Marín (@squat), Bartlomiej Plotka (@bwplotka)
- Issue: https://github.com/thanos-io/thanos/issues/2488

#### Per Request Query Tracking and Limiting

- Description: Thanos is at the very high-level: durable and cheap database capable of storing a very large amount of metric data. This means that querying that data can be expensive. Imagine someone queries years of data for millions of series. No matter how fast or efficient our indexing is, even the amount of data being passed through the network can get expensive. This is why users should have control, potentially someday per tenant to tell what query was performed, for how long and how much data it was using, and what happened or error. Users should also be able to limit such large queries.
Recommended Skills: go, distributed systems, Linux
- Mentor(s): Bartek Plotka (@bwplotka), Kemal Akkoyun (@kakkoyun)
- Issue: https://github.com/thanos-io/thanos/issues/1706 and https://github.com/thanos-io/thanos/issues/2527

### Complete Katacoda tutorials

- Description: This is a great project for a writer with some passion for Docker and Kubernetes, interested in doing interactive docs: specifically learning to build [Katacoda Course](https://katacoda.com/scenario-examples/scenarios/create-course). Currently, we have a single [Katacoda](https://katacoda.com/bwplotka/courses/thanos/1-globalview) tutorial, which helps Thanos users to start up quickly and understand the concepts. To help improve the user experience further we have planned five more tutorials. The Katacoda tutorials are written in YAML format and don't require a lot of custom tooling. We have a moderate amount of docs on our website [thanos.io](https://thanos.io/), which should help you to get started quickly. Also, there are many youtube videos explaining the concepts. We can offer friendly community support and technical guidance and feedback.
We're looking for one contributor to explore interactive tutorials and learn some technical concepts along the way. We are definitely not looking for perfection on the first try. Writing interactive tutorials:
  * Intro: Downsampling and unlimited metric retention for Prometheus
  * Intro: Global and meta alerts with Thanos
  * Advanced: Connecting remote Prometheuses to Thanos using simple Envoy setup.
  * Advanced: Using Prometheus remote write to stream metrics to Thanos
  * Advanced: Query low tail latency with low cost: Introducing caching to Thanos
Recommended Skills: Distributed systems, Linux, Kubernetes, Docker
- Mentor(s): Bartek Plotka (@bwplotka), Povilas Versockas (@povilasv)
- Issue: https://github.com/thanos-io/thanos/issues/2041

### Prometheus

#### Persist Retroactive Rule Reevaluations

- Description: Right now one of the biggest issues with recording rules is that data is only available since the rule was created. Which means any dashboards that use the recording rule will not have data prior to the recording rules create time. We can already reevaluate queries on old data, but we should be able to persist that for a certain window from [Oldest, Now).
- Recommended Skills: Golang
- Mentor(s): Bartlomiej Plotka (@bwplotka), Callum Styan (@cstyan)
- Issue: https://github.com/prometheus/prometheus/issues/11.

#### Remote Write WAL Pointer + Other Improvements

- Description: Remote write has gone through a rewrite in the last year, but there are still open improvements and feature additions that can be explored. For example, because remote write now sends data via Prometheus' WAL, the pointer for each remote write queue into the WAL should be persisted across restarts. The addition of new record types, or a new remote write specific WAL, so that new data not currently part of the WAL can be remote written coulda also be investigated.
- Recommended Skills: Golang, database and dist. systems nice to have.
- Mentor(s): Callum Styan (@cstyan), Chris Marchbanks (@csmarchbanks)
- Issue: https://github.com/prometheus/prometheus/issues/6333

### Envoy

#### Enrich Envoy stats with header size histogram

- Description: Currently there is lack of visibility into size of request headers that are proxied through Envoy. Adding corresponding histogram would increase observability for Envoy based systems.
- Recommended Skills: C++
- Mentor(s): Kateryna Nezdolii (@nezdolik)
- Issue: https://github.com/envoyproxy/envoy/issues/10308.

### Service Mesh Interface

#### SMI Conformance Testing

- Description: Ensure that a service mesh is properly configured and that its behavior conforms to official SMI specifications. Conformance consists of both capabilities and compliance status as outlined in the [design specification](https://docs.google.com/document/d/1HL8Sk7NSLLj-9PRqoHYVIGyU6fZxUQFotrxbmfFtjwc/edit).
- Recommended Skills**: Golang (nice to have: Kubernetes, Service Mesh)
- Mentor(s): Lee Calcote ([@lcalcote](https://twitter.com/lcalcote)), Vinayak Shinde ([@vinushnd](https://twitter.com/vinushnd))
- Issue: [https://github.com/servicemeshinterface/smi-spec/issues/70](https://github.com/servicemeshinterface/smi-spec/issues/70)

### TiKV

#### Full Chunk-based Computing

- Description: Currently, TiKV uses a simple but inefficient memory layout in computing framework. Using Chunk, a column-based memory layout, could improve memory locality and reduce memory allocation during expression evaluation.
- Recommended Skills: Rust, Database
- Mentor(s): Tianyi Zhuang (@TennyZhuang), breeswish (@breeswish)
- Upstream Issue (URL): https://github.com/tikv/tikv/issues/7724

### OpenEBS

#### A easy to use command-line interface (CLI) for OpenEBS.

- Description: OpenEBS is completely Kubernetes native and is implemented using microservices. OpenEBS can be installed via kubectl or helm chart and managed via custom resources. To improve the usability of OpenEBS, the proposal is to have a easy to use OpenEBS CLI (similar to `kubectl`) to perform operations like:
  - install  => Install OpenEBS
  - upgrade  => Upgrade OpenEBS components
  - status   => Print the readiness of various components, verify prerequisites are met to run openebs pools and volumes.
  - version  => Print the OpenEBS version and associated images
  - describe => Describe OpenEBS resources like pools and volumes.
  - create   => Create OpenEBS resources
  - delete   => Delete OpenEBS resources

- Recommended Skills: Go, Kubernetes
- Mentor(s): Kiran Mova (@kmova)
- Related Issues:
  - https://github.com/openebs/openebs/issues/2946
  - https://github.com/openebs/openebs/issues/1248
  - https://github.com/openebs/openebs/issues/290

#### Multiarch support for OpenEBS Docker images

- Description: OpenEBS Supports automated builds for amd64 and arm64. It will be good to make use of the "docker manifest" command to link different arch images into a single docker repository. This should allow kubernetes nodes to pull in the required container images.
- Recommended Skills: Docker, Shell, Makefile
- Mentor(s): Kiran Mova (@kmova)
- Related Issues:
  - https://github.com/openebs/openebs/issues/3023

#### New storage backend using raw disk images

- Description: OpenEBS Dynamic Local PV with Hostpath are great for use cases with low latency requirements and running on nodes with few attached drives or block devices. Using bare hostpath has the limitation of enforcing the capacity limits requested by PVC. The proposal is to implement a new type of storage, backed by a raw disk image on the host, that is mounted inside the pod. The storage backend should:
  - have near-zero performance overhead, compared to using local disks
  - be thin-provisioned
  - be able to enforce storage size limits
  - be able to expose volume metrics

- Recommended Skills: Kubernetes, Linux, Python, Go
- Mentor(s): Kiran Mova (@kmova)
- Related Issues:
  - https://github.com/openebs/openebs/issues/2871

### KubeEdge

#### Support metrics-server in cloud

- Description: Now we have integrated cadvisor in edge, and it also needs to integrate metrics-server in the cloud to collect monitoring data of edge nodes.
- Recommended Skills: Golang
- Mentor(s): Kevin Wang (@kevin-wangzefeng)
- Related Issues:
  - https://github.com/kubeedge/kubeedge/issues/1561

#### Add certificate rotation for edge node

- Description: At present, the edge nodes of KubeEdge only apply for certificates when they first started. And we need to automatically generate a new key and request a new certificate from the cloudcore periodically.
- Recommended Skills: Golang
- Mentor(s): Fisher Xu (@fisherxu)
- Related Issues:
  - https://github.com/kubeedge/kubeedge/issues/1630

### Fluentd
##### Fluent Bit Monitoring: Web UI

- Description:  Fluent Bit exposes internal metrics from the data processing pipeline through its HTTP interface. This project aims to build a Web UI to show the components of the data pipeline and its continuous metrics with dashboards and further info. The metrics are exposed in JSON format and should be scrapped by the UI. The UI can be deployable on any HTTP server without the need for NodeJS.

  Please refer to the Upstream Issue link for more details and candidate requirements.
-	Recommended Skills: Javascript, VueJS, CSS, HTML & general design skills
-	Mentor(s): Eduardo Silva (@edsiper)
-	Upstream Issue (URL): https://github.com/fluent/fluent-bit/issues/2147

### CoreDNS

##### External health check and orchestration of CoreDNS in Kubernetes clusters**

- Description: CoreDNS is the cluster DNS server for Kubernetes and is very much critical for the overall health of the Kubernetes cluster. It is very important to monitoring the health of CoreDNS itself and restarting or repairing any CoreDNS pods that are not behaving correctly. While CoreDNS exposes a health check itself, the health check is not UDP (DNS) based. The existing health check is also launched locally which could be very much different when accessed by other pods remotely.
  This project intends to build an application that checks CoreDNS health through UDP (DNS) externally, and, restart CoreDNS pods by interacting with Kubernetes API through golang. This is an important project that will greatly improve the overall health of Kubernetes clusters through automation.
- Recommended Skills:  Go, DNS, Kubernetes
- Mentor(s): Yong Tang (@yongtang), Paul Greenberg (@greenpau)
- Implementation: The deliverable of this project is a golang program that could be deployed in a Kubernetes cluster independently while at the same time, monitoring CoreDNS pods in the same cluster and interacting Kubernetes API (server) to restart CoreDNS pods as needed.
- Related Issues:
  - https://github.com/coredns/rfc/issues/7

### Linkerd

#### Egress Metrics

-	Description: Linkerd provides rich metrics for traffic inside the mesh. As most external services utilize HTTPS, it is unable to provide metrics today. This project intends to provide visibility into the traffic that is leaving clusters and surface metrics for that traffic.
-	Recommended Skills: golang, Kubernetes
-	Mentor(s): Thomas Rampelberg (@grampelberg)
-	Issue:
	- https://github.com/linkerd/linkerd2/issues/3190

#### Service Topologies

- Description: It is valuable to have metadata related to the topology of a cluster when making load balancing decisions. This metadata can be used to control egress costs between regions or even make advanced routing decisions in multicluster situations. As part of Kubernetes 1.17, [service topology](https://kubernetes.io/docs/concepts/services-networking/service-topology/) landed. This provides extra metadata as part of endpoints for a service to control weighting. Imagine transparently failing over to nodes running in a different zone if the pods locally are no longer running. Linkerd should implement support for this functionality.
- Recommended Skills: golang, Kubernetes, rust, Tokio
- Mentor(s): Thomas Rampelberg (@grampelberg)
- Issue:
  - https://github.com/linkerd/linkerd2/issues/4325

#### PCAP-NG Export

- Description: It is difficult to debug what is happening to the network traffic for workloads on Kubernetes. Linkerd provides tap and stat to provide some glimpses into what's happening. Many times, this is enough. Unfortunately, when low level problems and protocol issues crop up, the existing tools are not enough. This causes users to inject the debug container and tcpdump traffic on a pod by pod basis. This project will add PCAP-NG as an export format for tap. This can then be dumped locally or forwarded to Wireshark for analysis and debugging.
- Recommended Skills: golang, Kubernetes, rust, Tokio
- Mentor(s): Thomas Rampelberg (@grampelberg)
- Issue:
  - https://github.com/linkerd/linkerd2/issues/4326

#### Granular RBAC for Metrics

- Description: Kubernetes is a multitenant system, many users can interact without seeing what others are working with. Today, Linkerd runs a single control plane per cluster. This results in the metrics collected being stored in a single backend (Prometheus). In some high security environments, this means that the users of the cluster are unable to get the benefit of Linkerd's rich metrics. This project will introduce Kubernetes based, granular RBAC so that cluster operators can control what end users are able to view.
- Recommended Skills: golang, Kubernetes, Prometheus
- Mentor(s): Thomas Rampelberg (@grampelberg)
- Issue:
  - https://github.com/linkerd/linkerd2/issues/3312

#### Kafka Proxy Codec

- Description: HTTP based traffic is only one type of modern applications. Many use message queues such as Kafka. Getting the metrics for consumers/producers/messages are just as critical to application health as requests and responses in HTTP. This project will implement a Kafka codec that allows the Linkerd proxy to introspect Kafka's protocol and provide metrics for the communications between consumers and producers. This should show up as a CLI command, dashboard and visualization of the topology between message consumers and HTTP actors.
- Recommended Skills: golang, Kubernetes, rust, Tokio, Kafka
- Mentor(s): Thomas Rampelberg (@grampelberg)
- Issue:
  - https://github.com/linkerd/linkerd2/issues/2214

#### JWT Authentication

- Description: Linkerd implements service-service authentication today via. mTLS. This does not yet extend to user based authentication. This project will implement JWT authentication to provide applications using the service mesh a method for implementing authorization on a per-user basis.
- Recommended Skills: golang, Kubernetes, rust, Tokio
- Mentor(s): Thomas Rampelberg (@grampelberg)
- Issue:
  - https://github.com/linkerd/linkerd2/issues/3704

#### Network Diagnostics

- Description: It can be challenging to diagnose why things aren't working in a remote cluster. Is there a connectivity issue? What happens when a specific request is sent to a service? How do I work with the data that comes back? Linkerd should make this kind of interaction with a cluster's traffic easy and seamless. This project introduces a new command to the CLI: `exec`. This will wire up the networking locally for a user where local binaries (such as curl or ping) can interact with a Kubernetes cluster natively. It will use local binaries and produce local output to allow users to use their local tools and files to diagnose what's going on with their cluster.
- Recommended Skills: golang, Kubernetes
- Mentor(s): Thomas Rampelberg (@grampelberg)
- Issue:
  - https://github.com/linkerd/linkerd2/issues/4327

### KubeVirt

#### Kernel boot

-	Description: KubeVirt allows to boot from regular (virtual) disks, an alternative booting method is to directly provide a kernel, initrd, and cmdline to a VM for booting. Such a feature is generally useful for many unikernel projects like the European Project Unicore. This project is about defining the relevant API and adding the necessary kernel boot support to KubeVirt.
-	Recommended Skills: golang, Kubernetes, virtualization
-	Mentor(s): Daniel Belenky (@danielBelenky)
-	Issue:
	- https://github.com/kubevirt/kubevirt/issues/2741

#### Improve Observability
-	Description: KubeVirt is running VMs on Kubernetes, in order to simplify operations, KubeVirt should expose more metrics about the VMs (workloads) and it's infrastructure components, in order to improve serviceability by integrating with projects like prometheus. This project is about adding a couple of more metrics to different KubeVirt components.
-	Recommended Skills: golang, Kubernetes
-	Mentor(s): Daniel Belenky (@danielBelenky)
-	Issue:
	- https://github.com/kubevirt/kubevirt/issues/3385


text:
module AppetiteTest__Halt

  class App < Appetite

    def haltme
      args = []
      (status = params['status']) && args << status.to_i
      (body = params['body']) && args << body
      halt *args
    end

    def post_send_response status, body
      halt [status.to_i, request.POST, [body]]
    end

  end

  Spec.new App do

    Describe 'sending status and body' do
      r = get :haltme, :status => 500, :body => :fatal_error!
      expect(r.status) == 500
      is?(r.body) == 'fatal_error!'
    end

    Ensure 'it accepts empty body' do
      r = get :haltme, :status => 301
      expect(r.status) == 301
      is?(r.body) == ''
    end

    Ensure 'default status code is 200' do
      r = get :haltme, :body => 'halted'
      expect(r.status) == 200
      is?(r.body) == 'halted'
    end

    Ensure 'it works without arguments' do
      r = get :haltme
      expect(r.status) == 200
      is?(r.body) == ''
    end

    Testing 'custom response' do
      r = post :send_response, 301, 'redirecting...', 'Location' => 'http://to.the.sky'
      expect(r.status) == 301
      expect(r.body) == 'redirecting...'
      is?(r.header['Location']) == 'http://to.the.sky'
    end

  end
end


text:
import { Component, OnInit,  } from '@angular/core';
import { Http, Response } from '@angular/http';
import 'rxjs/add/operator/toPromise';

declare var moment: any;
/**
 * This class represents the lazy loaded HomeComponent.
 */
@Component({
  moduleId: module.id,
  selector: 'sd-home',
  templateUrl: 'home.component.html',
  styleUrls: ['home.component.css'],
})

/**
 * This class sets up the home page
 */
export class HomeComponent implements OnInit {

  height: number;
  breakdownAreas: Array<String> = [];
  predNowJson: Object;
  maxJson: Object;
  totalOccupancy: Number = 0;
  dateJson: Object;
  lastUpdatedMinutes: Number;
  lastUpdatedHours: Number;
  lastUpdatedDays: Number;
/*
  newName: string = '';
  errorMessage: string;
  names: any[] = [];
*/

  //Get the names OnInit
  constructor(private http: Http){

  }

  //Json reader
  getData(fileName: string): Promise<any> {
      return this.http.get(fileName)
                 .toPromise()
                 .then(response => response.json())
                 .catch(this.handleError);
  }

  private handleError(error: any): Promise<any> {
      console.error('An error occurred', error); // for demo purposes only
      return Promise.reject(error.message || error);
  }

  //Reads json
  ngOnInit() {
    this.height = 0;
        this.getData("active.json").then(data => {
            this.maxJson = data[1];
            this.getData("predictionsNow.json").then(data => {
                this.predNowJson = data;
                for (var item in data){
                    this.breakdownAreas.push(item);
                    this.totalOccupancy = this.totalOccupancy + data[item];
                }
                this.breakdownAreas.sort();
                this.getData("date.json").then(data => {
                    this.dateJson = data;

                    var lastUpdateDate = moment(this.dateJson, "YYYY-MM-DD HH-mm");

                    var duration = moment.duration(moment().diff(lastUpdateDate));
                    var days = parseInt(duration.asDays());
                    var hours = parseInt(duration.asHours()) - days * 24;
                    var minutes = parseInt(duration.asMinutes()) - (days * 24 * 60) - (hours*60) ;
                    this.lastUpdatedDays = days;
                    this.lastUpdatedHours = hours;
                    this.lastUpdatedMinutes = minutes;
                });
            });
        });
  }

  //Scroll when breakdown clicked
  scrollDown() {
    var div = document.getElementById('el');
    if (div.style.display == 'none') {
        div.style.display = 'block';
    } else {
        div.style.display = 'none';
    }
    // if (this.height == 0) {
    //   this.height = document.getElementById("el").scrollHeight;
    // } else {
    //   this.height = 0;
    // }
    document.getElementById('breakdown').scrollIntoView({behavior: 'smooth'});
    //this.height = this.height ? 0 : document.getElementById("el").scrollHeight;
  }
}


text:
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.EventSystems;
using System.Collections;

namespace UIWidgets
{
	/// <summary>
	/// SelectEvent.
	/// </summary>
	[System.Serializable]
	public class SelectEvent : UnityEvent<BaseEventData> {

	}

	/// <summary>
	/// Deselect listener.
	/// </summary>
	public class SelectListener : MonoBehaviour, ISelectHandler, IDeselectHandler
	{
		/// <summary>
		/// The OnSelect event.
		/// </summary>
		public SelectEvent onSelect = new SelectEvent();

		/// <summary>
		/// The OnDeselect event.
		/// </summary>
		public SelectEvent onDeselect = new SelectEvent();

		/// <summary>
		/// Raises the select event.
		/// </summary>
		/// <param name="eventData">Event data.</param>
		public void OnSelect(BaseEventData eventData)
		{
			onSelect.Invoke(eventData);
		}

		/// <summary>
		/// Raises the deselect event.
		/// </summary>
		/// <param name="eventData">Event data.</param>
		public void OnDeselect(BaseEventData eventData)
		{
			onDeselect.Invoke(eventData);
		}
	}
}


text:
<?php

namespace AppBundle\Entity;

use AppBundle\EntityTraits\BrMoTyTrait;
use Doctrine\ORM\Mapping as ORM;

/**
 * Modèle de la voiture
 *
 * @ORM\Table(name="model")
 * @ORM\Entity(repositoryClass="AppBundle\Repository\ModelRepository")
 *
 * @author Dominick Makome <makomedominick@gmail.com>
 */
class Model
{
    use BrMoTyTrait;

    /**
     * @var TypeCar
     * @ORM\ManyToOne(targetEntity="AppBundle\Entity\Brand", inversedBy="models")
     */
    private $brand;

    /**
     * @return Brand
     */
    public function getBrand()
    {
        return $this->brand;
    }

    /**
     * @param Brand $brand
     */
    public function setBrand(Brand $brand)
    {
        $this->brand = $brand;

        return $this;
    }

    /**
     * Get id
     *
     * @return int
     */
    public function getId()
    {
        return $this->id;
    }
}


text:
#include <stdint.h>
#include <string.h>
#include "asc_coordinator.h"
#include "asc_events.h"
#include "asc_parameters.h"
#include "asc_master_to_master.h"
#include "asc_master.h"
#include "ant_phone_connection.h"
#include "ant_interface.h"
#if 1 // @todo: remove me
#include "nordic_common.h" //Included here because softdevice_handler.h requires it but does not include it, itself
#include "softdevice_handler.h"
#endif // 0
#include "ant_parameters.h"
#include "app_error.h"
#include "leds.h"
#include "boards.h"
#include "ant_stack_config.h"

#ifdef BLE_STACK_SUPPORT_REQD
#if 1 // @todo: remove me
    #include "ble_stack_handler_types.h"
#endif // 0
    #include "ble_controllable_hub.h"
    #include "ble_phone_connection.h"
#endif

#if defined(BOARD_N5DK1)
    #define LED_CONNECT_STATUS   LED_B
#else
    #define LED_CONNECT_STATUS   BSP_LED_1
#endif

//Generic Channel properties
#define ANT_PUBLIC_NETWORK_NUMBER       0x00u                       /**< ANT Public/Default Network Key. */
#define ANT_CUSTOM_TRANSMIT_POWER       0u                          /**< ANT Custom Transmit Power (Invalid/Not Used). */
#define SERIAL_NUMBER_ADDRESS           ((uint32_t) 0x10000060)     // FICR + 60
#define DEVICE_NUMBER                   (*(uint16_t*) SERIAL_NUMBER_ADDRESS)

// ASCM Channel configuration.
#define ASCM_CHANNEL                    0x00u                       /**< ASC Master channel. */
#define ASCM_RF_FREQUENCY               0x42u                       /**< 2400 + 66Mhz. */
#define ASCM_CHANNEL_PERIOD             MSG_PERIOD_4HZ              /**< ASC Master channel period. */
#define ASCM_CHANNEL_TYPE               CHANNEL_TYPE_MASTER         /**< ASC Master channel type. */
#ifdef TWO_BYTE_SHARED_ADDRESS
    #define ASCM_TRANS_TYPE             ANT_TRANS_TYPE_2_BYTE_SHARED_ADDRESS    /**< Two byte shared address transmission type. */
#else
    #define ASCM_TRANS_TYPE             ANT_TRANS_TYPE_1_BYTE_SHARED_ADDRESS    /**< One byte shared address transmission type. */
#endif
#define ASCM_DEVICE_TYPE                0x02u                       /**< Device type. */
#define DEFAULT_RETRIES                 2u                          /**< The default number of retries that this demo will tell an ASC Master to attempt when sending a command to all slaves. */

// Phone Channel configuration.
#define PHONE_CHANNEL                   0x01u                       /**< Phone connection channel. */
#define PHONE_RF_FREQUENCY              0x42u                       /**< Phone connection rf frequency offset. */
#define PHONE_CHANNEL_PERIOD            MSG_PERIOD_4HZ              /**< Phone connection channel period. */
#define PHONE_CHANNEL_TYPE              CHANNEL_TYPE_MASTER         /**< Phone connection channel type. */
#define PHONE_TRANS_TYPE                0x05u                       /**< Phone connection transmission type. */
#define PHONE_DEVICE_TYPE               0x03u                       /**< Phone connection device type. */

// Master to Master Channel configuration.
#define ASCMM_DISCOVERY_CHANNEL         0x02u                       /**< Master to Master device discovery channel. */
#define ASCMM_CHANNEL                   0x03u                       /**< Master to Master channel. */
#define ASCMM_RF_FREQUENCY              0x42u                       /**< Master to Master rf frequency offset (same as PHONE_RF_FREQUENCY since the phone connection channel is used for discovery). */
#define ASCMM_CHANNEL_PERIOD            MSG_PERIOD_4HZ              /**< Master to Master channel period (same as PHONE_CHANNEL_PERIDO since the phone connection channel is used for discovery). */
#define ASCMM_CHANNEL_TYPE              CHANNEL_TYPE_SLAVE          /**< Master to Master channel type. */
#define ASCMM_TRANS_TYPE                0x05u                       /**< Master to Master  transmission type (same as PHONE_TRANS_TYPE since the phone connection channel is used for discovery). */
#define ASCMM_DEVICE_TYPE               0x04u                       /**< Master to Master device type (same as PHONE_DEVICE_TYPE since the phone connection channel is used for discovery). */
#define ASCMM_RETRIES                   0x02                        /**< Number of messages retries that will be sent when relaying messages. */

#define IS_SRVC_CHANGED_CHARACT_PRESENT 0                                            /**< Whether or not to include the service_changed characteristic. If not enabled, the server's database cannot be changed for the lifetime of the device */

// Static variables and buffers.
static uint16_t         m_neighbor_id = INVALID_NEIGHBOUR_ID;
static bool             m_is_reporting_mode_on = true;
static uint8_t          m_ant_public_network_key[] = {0xE8, 0xE4, 0x21, 0x3B, 0x55, 0x7A, 0x67, 0xC1}; /**< ANT Public/Default Network Key. */
static uint8_t          m_tx_buffer[ANT_STANDARD_DATA_PAYLOAD_SIZE] = {0};

const asc_ant_params_t  m_asc_parameters = {
    ASCM_CHANNEL,
    ANT_PUBLIC_NETWORK_NUMBER,
    (uint16_t*) SERIAL_NUMBER_ADDRESS,
    ASCM_DEVICE_TYPE,
    ASCM_TRANS_TYPE,
    ASCM_CHANNEL_PERIOD,
    ASCM_CHANNEL_TYPE,
    ASCM_RF_FREQUENCY,
    RADIO_TX_POWER_LVL_3
}; /**< Structure containing setup parameters for the auto shared master. */

const asc_ant_params_t  m_ascmm_discovery_parameters = {
    ASCMM_DISCOVERY_CHANNEL,
    ANT_PUBLIC_NETWORK_NUMBER,
    (uint16_t*) SERIAL_NUMBER_ADDRESS,
    PHONE_DEVICE_TYPE,
    PHONE_TRANS_TYPE,
    PHONE_CHANNEL_PERIOD,
    CHANNEL_TYPE_SLAVE,
    PHONE_RF_FREQUENCY,
    RADIO_TX_POWER_LVL_3
}; /**< Structure containing setup parameters for the discovery portion of the master-to-master connection.
        In this case, it searches for the phone connection channel. */

const asc_ant_params_t  m_ascmm_connection_parameters = {
    ASCMM_CHANNEL,
    ANT_PUBLIC_NETWORK_NUMBER,
    (uint16_t*) SERIAL_NUMBER_ADDRESS,
    ASCMM_DEVICE_TYPE,
    ASCMM_TRANS_TYPE,
    ASCMM_CHANNEL_PERIOD,
    ASCMM_CHANNEL_TYPE,
    ASCMM_RF_FREQUENCY,
    RADIO_TX_POWER_LVL_3
}; /**< Structure containing setup parameters for the final master-to-master connection. */

const asc_ant_params_t  m_phone_parameters = {
    PHONE_CHANNEL,
    ANT_PUBLIC_NETWORK_NUMBER,
    (uint16_t*) SERIAL_NUMBER_ADDRESS,
    PHONE_DEVICE_TYPE,
    PHONE_TRANS_TYPE,
    PHONE_CHANNEL_PERIOD,
    PHONE_CHANNEL_TYPE,
    PHONE_RF_FREQUENCY,
    RADIO_TX_POWER_LVL_3
}; /**< Structure containing setup parameters for the phone connection. */

#if defined(BLE_STACK_SUPPORT_REQD) && defined (TWO_BYTE_SHARED_ADDRESS)
#error "BLE Demo is incompatible with two byte shared addressing."
#endif

// Private Functions

/**@brief Function to get and handle ant events.
 */
void poll_for_ant_events(void)
{
    static uint32_t err_code;
    static uint8_t  event;
    static uint8_t  ant_channel;
    static uint8_t  event_message_buffer[MESG_BUFFER_SIZE];

    err_code = sd_ant_event_get(&ant_channel, &event, event_message_buffer);
    if (err_code == NRF_SUCCESS)
    {
        switch(ant_channel)
        {
            case ASCM_CHANNEL:
            {
                ascm_handle_ant_event(event, event_message_buffer);
                break;
            }
            case ASCMM_DISCOVERY_CHANNEL:
                //intentional fallthrough
            case ASCMM_CHANNEL:
            {
                ascmm_handle_ant_event(event, event_message_buffer);
                break;
            }
            case PHONE_CHANNEL:
            {
                phc_handle_ant_event(event, event_message_buffer);
                break;
            }
            default:
            {
                break;
            }
        }
    }
}

/**@breif  Function for checking event flags and handling them.
 */
void check_and_handle_ascm_flags(void)
{
    uint32_t asc_flags = ascm_events_get();
    uint32_t registry_flags = ascm_get_device_registry_events();

    do
    {
        //service asc master events
        if (asc_flags & EVENT_ASC_STATE_CHANGED)
        {
            ascm_event_clear(EVENT_ASC_STATE_CHANGED);

            //determine which state the master has moved into and handle it
            ascm_states_t state = ascm_state_get();
            switch(state)
            {
                case SENDING_COMMAND:
                case ASCM_OFF:
                case ADDRESS_AVAILABLE:
                case HANDSHAKING:
                case POLLING:
                default:
                    break;
            }
        }

        if(asc_flags & EVENT_ASC_DEVICE_IN_WRONG_STATE)
        {
            ascm_event_clear(EVENT_ASC_DEVICE_IN_WRONG_STATE);
            //Do Nothing
        }

        if(asc_flags & EVENT_ASC_UPDATE_RECEIVED)
        {
            ascm_event_clear(EVENT_ASC_UPDATE_RECEIVED);

            if(m_is_reporting_mode_on)
            {
                //extract last update and relay the update accross the master to master channel
                asc_update_data_t update = ascm_get_last_recevied_update();
                update.master_id = DEVICE_NUMBER;
                asc_encode_phone_update_data_page(update, m_tx_buffer);
                ascmm_relay_message(m_tx_buffer, DEFAULT_RETRIES);

                //also send this update across the phone channel
                phc_transmit_message(m_tx_buffer, DEFAULT_RETRIES);
#ifdef BLE_STACK_SUPPORT_REQD
                cntrldevice_process_update(update);
#endif
            }
        }

        //service device registry events
        if(registry_flags & DEVICEREGISTRY_EVENT_DEVICE_ADDED)
        {
            ascm_clear_device_registry_event(DEVICEREGISTRY_EVENT_DEVICE_ADDED);
        }

        if(registry_flags & DEVICEREGISTRY_EVENT_DEVICE_REMOVED)
        {
            ascm_clear_device_registry_event(DEVICEREGISTRY_EVENT_DEVICE_REMOVED);
        }

        //update the local events bitfields
        asc_flags = ascm_events_get();
        registry_flags = ascm_get_device_registry_events();
    }
    while(asc_flags != 0 && registry_flags !=0);

}

void check_and_handle_ascmm_flags(void)
{
    uint32_t ascmm_flags = ascmm_events_get();

    do
    {
        //service master to master events
        if(ascmm_flags & EVENT_ASC_STATE_CHANGED)
        {
            ascmm_event_clear(EVENT_ASC_STATE_CHANGED);
            m_neighbor_id = ascmm_get_neighbor_id();
            phc_set_neighbor_id(m_neighbor_id);

            ascmm_states_t state = ascmm_state_get();
            switch(state)
            {
                case CONNECTED:
                {
                    led_on(LED_CONNECT_STATUS);
                    break;
                }
                default:
                {
                    led_off(LED_CONNECT_STATUS);
                    break;
                }
            }
        }

        if(ascmm_flags & EVENT_ASC_DEVICE_IN_WRONG_STATE)
        {
            ascmm_event_clear(EVENT_ASC_DEVICE_IN_WRONG_STATE);
            //Do nothing
        }

        if(ascmm_flags & EVENT_ASC_COMMAND_RECEIVED)
        {
            ascmm_event_clear(EVENT_ASC_COMMAND_RECEIVED);

            asc_command_data_t command_data =  ascmm_get_last_command();

            switch(command_data.command)
            {
                case REPORTING_MODE_OFF:
                {
                    m_is_reporting_mode_on = false;
                    break;
                }
                case REPORTING_MODE_ON:
                {
                    m_is_reporting_mode_on = true;
                    break;
                }
                default:
                {
//lint --e{534}
                    ascm_send_command(command_data, DEFAULT_RETRIES);
                    break;
                }
            }
        }

        if(ascmm_flags & EVENT_ASC_UPDATE_RECEIVED)
        {
            ascmm_event_clear(EVENT_ASC_UPDATE_RECEIVED);

            if(m_is_reporting_mode_on)
            {
                //Get the received update and relay it to the phone
                asc_update_data_t update = ascmm_get_last_update();
                asc_encode_phone_update_data_page(update, m_tx_buffer);
                phc_transmit_message(m_tx_buffer, DEFAULT_RETRIES);
#ifdef BLE_STACK_SUPPORT_REQD
                cntrldevice_process_update(update);
#endif
            }
        }

        //update the local events bitfields
        ascmm_flags = ascmm_events_get();
    }
    while(ascmm_flags != 0);
}

void handle_received_command(asc_command_data_t command_data)
{
    switch(command_data.command)
    {
        case REPORTING_MODE_OFF:
        {
            m_is_reporting_mode_on = false;
            asc_encode_phone_command_page(command_data, m_tx_buffer);
            ascmm_relay_message(m_tx_buffer, ASCMM_RETRIES);
            break;
        }
        case REPORTING_MODE_ON:
        {
            m_is_reporting_mode_on = true;
            asc_encode_phone_command_page(command_data, m_tx_buffer);
            ascmm_relay_message(m_tx_buffer, ASCMM_RETRIES);
            break;
        }
        default:
        {
            if (command_data.master_id == DEVICE_NUMBER)
            {
//lint --e{534}
                ascm_send_command(command_data, DEFAULT_RETRIES);
            }
            else if (command_data.master_id == m_neighbor_id && m_neighbor_id != INVALID_NEIGHBOUR_ID)
            {
                asc_encode_phone_command_page(command_data, m_tx_buffer);
                ascmm_relay_message(m_tx_buffer, ASCMM_RETRIES);
            }
            else if (command_data.master_id == EVERY_MASTER_ID)
            {
//lint --e{534}
                ascm_send_command(command_data, DEFAULT_RETRIES);
                asc_encode_phone_command_page(command_data, m_tx_buffer);
                ascmm_relay_message(m_tx_buffer, ASCMM_RETRIES);
            }
            break;
        }
    }
}

void check_and_handle_phc_flags(void)
{
    uint32_t phone_connection_flags = phc_events_get();

    do
    {
        //service phone connection events
        if(phone_connection_flags & EVENT_ASC_COMMAND_RECEIVED)
        {
            phc_event_clear(EVENT_ASC_COMMAND_RECEIVED);
            asc_command_data_t command_data = phc_get_last_command();

            handle_received_command(command_data);
        }

        phone_connection_flags = phc_events_get();
    }
    while(phone_connection_flags != 0);
}

#ifdef BLE_STACK_SUPPORT_REQD
void check_and_handle_ble_flags(void)
{
    uint32_t ble_flags = ble_achs_events_get();

    do
    {
        //service phone connection events
        if(ble_flags & EVENT_ASC_COMMAND_RECEIVED)
        {
            ble_achs_event_clear(EVENT_ASC_COMMAND_RECEIVED);
            asc_command_data_t command_data = ble_achs_get_last_command();

            handle_received_command(command_data);
        }

        ble_flags = ble_achs_events_get();
    }
    while(ble_flags != 0);
}

static void ble_evt_dispatch(ble_evt_t * p_ble_evt)
{
    cntrldevice_event_handler(p_ble_evt);
}

/**@brief BLE stack initialization.
 *
 * @details Initializes the SoftDevice and the stack event interrupt.
 */
static void ble_stack_init(void)
{
    uint32_t err_code;

    // Initialize SoftDevice
    SOFTDEVICE_HANDLER_INIT(NRF_CLOCK_LFCLKSRC, false);

    // Initialize BLE stack
    ble_enable_params_t ble_enable_params;
    memset(&ble_enable_params, 0, sizeof(ble_enable_params));
    ble_enable_params.gatts_enable_params.service_changed = IS_SRVC_CHANGED_CHARACT_PRESENT;
    err_code = sd_ble_enable(&ble_enable_params);
    APP_ERROR_CHECK(err_code);

    // Subscribe for BLE events.
    err_code = softdevice_ble_evt_handler_set(ble_evt_dispatch);
    APP_ERROR_CHECK(err_code);
}
#endif

// Public Functions

void ascc_init(void)
{
    uint32_t err_code;

#ifdef BLE_STACK_SUPPORT_REQD
    // Configure the ble stack and callback
    ble_stack_init();

    // Initialize the ble phone connection
    cntrldevice_initialize();
#endif

    err_code = ant_stack_static_config();
    APP_ERROR_CHECK(err_code);

    // Configure the network key for our chosen netowrk number
    err_code = sd_ant_network_address_set(ANT_PUBLIC_NETWORK_NUMBER, m_ant_public_network_key);
    APP_ERROR_CHECK(err_code);

    // Initialise and start the asc, ascmm, and phone modules
    ascm_init(&m_asc_parameters);
    ascmm_init(&m_ascmm_discovery_parameters, &m_ascmm_connection_parameters, DEVICE_NUMBER);
    phc_init(&m_phone_parameters);

    ascm_turn_on();
    ascmm_turn_on();
    phc_turn_on();
}

void ascc_poll_for_ant_evets(void)
{
    poll_for_ant_events();
    check_and_handle_ascm_flags();
    check_and_handle_ascmm_flags();
    check_and_handle_phc_flags();

#ifdef BLE_STACK_SUPPORT_REQD
    check_and_handle_ble_flags();
#endif
}


text:
package org.febit.leancloud.service;

import java.util.List;
import org.febit.form.PageForm;
import org.febit.service.PageResult;

/**
 * @author zqq90
 */
public final class LcPageResult implements PageResult {

    private final int page;
    private final int pageSize;
    private long totalSize;
    private List results;
    private Object links;

    public LcPageResult() {
        this(1, 10);
    }

    public LcPageResult(PageForm from) {
        this(from.getPage(), from.getLimit());
    }

    public LcPageResult(int page, int pageSize) {
        this.page = page;
        this.pageSize = pageSize;
    }

    public int getCurrSize() {
        return results != null ? results.size() : 0;
    }

    @Override
    public int getPage() {
        return page;
    }

    @Override
    public int getPageSize() {
        return pageSize;
    }

    @Override
    public List getResults() {
        return results;
    }

    @Override
    public void setResults(List results) {
        this.results = results;
    }

    @Override
    public long getTotalSize() {
        return totalSize;
    }

    @Override
    public void setTotalSize(long totalSize) {
        this.totalSize = totalSize;
    }

    @Override
    public Object getLinks() {
        return links;
    }

    @Override
    public void setLinks(Object links) {
        this.links = links;
    }

    @Override
    public int getTotalPage() {
        if (pageSize <= 0) {
            return 1;
        }
        return (int) (totalSize / pageSize + (totalSize % pageSize == 0 ? 0 : 1));
    }
}


text:
Bundle System especially for ReactJS Apps.

* **Universal:** Bundles your app for usage in the browser and uses the same transformers to compile the modules for nodeJS.
* **Multicore:** Takes 1/5 of the time of browserify (without cache)!

# Usage
```js
var path = require('path');
var unijsBundle = require('unijs-bundle');

unijsBundle({
	entryFile: require.resolve(path.join(__dirname, 'client', 'js', 'main.js')),
	swappers: [],
	transformers: [require.resolve('./babelTransformer.js')]
});
```

# More Documentation coming soon!


text:
#pragma once
#include <aws/xray/XRay_EXPORTS.h>
#include <aws/xray/XRayRequest.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <utility>

namespace Aws
{
namespace XRay
{
namespace Model
{

  /**
   */
  class AWS_XRAY_API ListResourcePoliciesRequest : public XRayRequest
  {
  public:
    ListResourcePoliciesRequest();

    // Service request name is the Operation name which will send this request out,
    // each operation should has unique request name, so that we can get operation's name from this request.
    // Note: this is not true for response, multiple operations may have the same response name,
    // so we can not get operation's name from response.
    inline virtual const char* GetServiceRequestName() const override { return "ListResourcePolicies"; }

    Aws::String SerializePayload() const override;

    /**
     *
Not currently supported.

     */
    inline const Aws::String& GetNextToken() const{ return m_nextToken; }

    /**
     *
Not currently supported.

     */
    inline bool NextTokenHasBeenSet() const { return m_nextTokenHasBeenSet; }

    /**
     *
Not currently supported.

     */
    inline void SetNextToken(const Aws::String& value) { m_nextTokenHasBeenSet = true; m_nextToken = value; }

    /**
     *
Not currently supported.

     */
    inline void SetNextToken(Aws::String&& value) { m_nextTokenHasBeenSet = true; m_nextToken = std::move(value); }

    /**
     *
Not currently supported.

     */
    inline void SetNextToken(const char* value) { m_nextTokenHasBeenSet = true; m_nextToken.assign(value); }

    /**
     *
Not currently supported.

     */
    inline ListResourcePoliciesRequest& WithNextToken(const Aws::String& value) { SetNextToken(value); return *this;}

    /**
     *
Not currently supported.

     */
    inline ListResourcePoliciesRequest& WithNextToken(Aws::String&& value) { SetNextToken(std::move(value)); return *this;}

    /**
     *
Not currently supported.

     */
    inline ListResourcePoliciesRequest& WithNextToken(const char* value) { SetNextToken(value); return *this;}

  private:

    Aws::String m_nextToken;
    bool m_nextTokenHasBeenSet = false;
  };

} // namespace Model
} // namespace XRay
} // namespace Aws


text:
import mongoengine

class MongoenginePlugin(object):
    name = 'mongoengine_ext'
    api = 2

    def setup(self, app):
        self.app = app
        mongoengine.connect(app.config['mongoengine.database'],
                            host=app.config['mongoengine.host'])

    def apply(self, callback, route):
        def wrapper(*args, **kwargs):
            return callback(*args, **kwargs)
        return wrapper


text:
import Ember from 'ember';

const { Route } = Ember;

export default Route.extend({
  titleToken: 'Validator usage'
});


text:
class CreateGalleryItems < ActiveRecord::Migration
  def self.up
    create_table :gallery_items do |t|
      t.string :title
      t.string :caption

      t.string :attachment_content_type
      t.string :attachment_file_name
      t.integer :attachment_size
      t.datetime :attachment_updated_at
      t.integer  :attachment_width
      t.integer  :attachment_height

      t.integer :gallery_id

      t.timestamps
    end
  end

  def self.down
    drop_table :gallery_items
  end
end