text:
using System;

namespace Svelto.ECS.Serialization
{
    public interface ISerializableEntityDescriptor : IDynamicEntityDescriptor
    {
        uint                            hash                { get; }
        ISerializableComponentBuilder[] componentsToSerialize { get; }
        Type                            realType            { get; }
    }
}

redpajama_set_name: RedPajamaGithub


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

namespace JM.LinqFaster
{
    public static partial class LinqFaster
    {
        // --------------------------  ARRAYS  --------------------------------------------

        /// <summary>
        ///  Adds a sequence of values.
        /// </summary>
        /// <param name="source">The sequence to add.</param>
        /// <returns>The sum of the sequence.</returns>
        public static int SumF(this int[] source)
        {
            if (source == null)
            {
                throw Error.ArgumentNull("source");
            }
            int sum = 0;
            checked
            {
                foreach (var v in source)
                {
                    sum += v;
                }
            }
            return sum;
        }

        /// <summary>
        /// Adds the transformed sequence of elements.
        /// </summary>
        /// <param name="source">The sequence of values to transform then sum.</param>
        /// <param name="selector">A transformation function.</param>
        /// <returns>The sum of the transformed elements.</returns>
        public static int SumF<T>(this T[] source, Func<T, int> selector)
        {
            if (source == null)
            {
                throw Error.ArgumentNull("source");
            }

            if (selector == null)
            {
                throw Error.ArgumentNull("selector");
            }

            int sum = 0;
            checked
            {
                foreach (var v in source)
                {
                    sum += selector(v);
                }
            }
            return sum;
        }

        /// <summary>
        ///  Adds a sequence of values.
        /// </summary>
        /// <param name="source">The sequence to add.</param>
        /// <returns>The sum of the sequence.</returns>
        public static long SumF(this long[] source)
        {
            if (source == null)
            {
                throw Error.ArgumentNull("source");
            }
            long sum = 0;
            checked
            {
                foreach (var v in source)
                {
                    sum += v;
                }
            }
            return sum;
        }

        /// <summary>
        /// Adds the transformed sequence of elements.
        /// </summary>
        /// <param name="source">The sequence of values to transform then sum.</param>
        /// <param name="selector">A transformation function.</param>
        /// <returns>The sum of the transformed elements.</returns>
        public static long SumF<T>(this T[] source, Func<T, long> selector)
        {
            if (source == null)
            {
                throw Error.ArgumentNull("source");
            }

            if (selector == null)
            {
                throw Error.ArgumentNull("selector");
            }

            long sum = 0;
            checked
            {
                foreach (var v in source)
                {
                    sum += selector(v);
                }
            }
            return sum;
        }

        /// <summary>
        ///  Adds a sequence of values.
        /// </summary>
        /// <param name="source">The sequence to add.</param>
        /// <returns>The sum of the sequence.</returns>
        public static float SumF(this float[] source)
        {
            if (source == null)
            {
                throw Error.ArgumentNull("source");
            }
            double sum = 0;

            foreach (var v in source)
            {
                sum += v;
            }

            return (float)sum;
        }

        /// <summary>
        /// Adds the transformed sequence of elements.
        /// </summary>
        /// <param name="source">The sequence of values to transform then sum.</param>
        /// <param name="selector">A transformation function.</param>
        /// <returns>The sum of the transformed elements.</returns>
        public static float SumF<T>(this T[] source, Func<T, float> selector)
        {
            if (source == null)
            {
                throw Error.ArgumentNull("source");
            }

            if (selector == null)
            {
                throw Error.ArgumentNull("selector");
            }

            double sum = 0;
            foreach (var v in source)
            {
                sum += selector(v);
            }

            return (float)sum;
        }

        /// <summary>
        ///  Adds a sequence of values.
        /// </summary>
        /// <param name="source">The sequence to add.</param>
        /// <returns>The sum of the sequence.</returns>
        public static double SumF(this double[] source)
        {
            if (source == null)
            {
                throw Error.ArgumentNull("source");
            }
            double sum = 0;
            foreach (var v in source)
            {
                sum += v;
            }

            return sum;
        }

        /// <summary>
        /// Adds the transformed sequence of elements.
        /// </summary>
        /// <param name="source">The sequence of values to transform then sum.</param>
        /// <param name="selector">A transformation function.</param>
        /// <returns>The sum of the transformed elements.</returns>
        public static double SumF<T>(this T[] source, Func<T, double> selector)
        {
            if (source == null)
            {
                throw Error.ArgumentNull("source");
            }

            if (selector == null)
            {
                throw Error.ArgumentNull("selector");
            }

            double sum = 0;
            foreach (var v in source)
            {
                sum += selector(v);
            }

            return sum;
        }

        /// <summary>
        ///  Adds a sequence of values.
        /// </summary>
        /// <param name="source">The sequence to add.</param>
        /// <returns>The sum of the sequence.</returns>
        public static decimal SumF(this decimal[] source)
        {
            if (source == null)
            {
                throw Error.ArgumentNull("source");
            }
            decimal sum = 0;

            foreach (var v in source)
            {
                sum += v;
            }

            return sum;
        }

        /// <summary>
        /// Adds the transformed sequence of elements.
        /// </summary>
        /// <param name="source">The sequence of values to transform then sum.</param>
        /// <param name="selector">A transformation function.</param>
        /// <returns>The sum of the transformed elements.</returns>
        public static decimal SumF<T>(this T[] source, Func<T, decimal> selector)
        {
            if (source == null)
            {
                throw Error.ArgumentNull("source");
            }

            if (selector == null)
            {
                throw Error.ArgumentNull("selector");
            }

            decimal sum = 0;
            foreach (var v in source)
            {
                sum += selector(v);
            }

            return sum;
        }

        /*---- Spans ---*/

        /// <summary>
        ///  Adds a sequence of values.
        /// </summary>
        /// <param name="source">The sequence to add.</param>
        /// <returns>The sum of the sequence.</returns>
        public static int SumF(this Span<int> source)
        {
            if (source == null)
            {
                throw Error.ArgumentNull("source");
            }
            int sum = 0;
            checked
            {
                foreach (var v in source)
                {
                    sum += v;
                }
            }
            return sum;
        }

        /// <summary>
        /// Adds the transformed sequence of elements.
        /// </summary>
        /// <param name="source">The sequence of values to transform then sum.</param>
        /// <param name="selector">A transformation function.</param>
        /// <returns>The sum of the transformed elements.</returns>
        public static int SumF<T>(this Span<T> source, Func<T, int> selector)
        {
            if (source == null)
            {
                throw Error.ArgumentNull("source");
            }

            if (selector == null)
            {
                throw Error.ArgumentNull("selector");
            }

            int sum = 0;
            checked
            {
                foreach (var v in source)
                {
                    sum += selector(v);
                }
            }
            return sum;
        }

        /// <summary>
        ///  Adds a sequence of values.
        /// </summary>
        /// <param name="source">The sequence to add.</param>
        /// <returns>The sum of the sequence.</returns>
        public static long SumF(this Span<long> source)
        {
            if (source == null)
            {
                throw Error.ArgumentNull("source");
            }
            long sum = 0;
            checked
            {
                foreach (var v in source)
                {
                    sum += v;
                }
            }
            return sum;
        }

        /// <summary>
        /// Adds the transformed sequence of elements.
        /// </summary>
        /// <param name="source">The sequence of values to transform then sum.</param>
        /// <param name="selector">A transformation function.</param>
        /// <returns>The sum of the transformed elements.</returns>
        public static long SumF<T>(this Span<T> source, Func<T, long> selector)
        {
            if (source == null)
            {
                throw Error.ArgumentNull("source");
            }

            if (selector == null)
            {
                throw Error.ArgumentNull("selector");
            }

            long sum = 0;
            checked
            {
                foreach (var v in source)
                {
                    sum += selector(v);
                }
            }
            return sum;
        }

        /// <summary>
        ///  Adds a sequence of values.
        /// </summary>
        /// <param name="source">The sequence to add.</param>
        /// <returns>The sum of the sequence.</returns>
        public static float SumF(this Span<float> source)
        {
            if (source == null)
            {
                throw Error.ArgumentNull("source");
            }
            double sum = 0;

            foreach (var v in source)
            {
                sum += v;
            }

            return (float)sum;
        }

        /// <summary>
        /// Adds the transformed sequence of elements.
        /// </summary>
        /// <param name="source">The sequence of values to transform then sum.</param>
        /// <param name="selector">A transformation function.</param>
        /// <returns>The sum of the transformed elements.</returns>
        public static float SumF<T>(this Span<T> source, Func<T, float> selector)
        {
            if (source == null)
            {
                throw Error.ArgumentNull("source");
            }

            if (selector == null)
            {
                throw Error.ArgumentNull("selector");
            }

            double sum = 0;
            foreach (var v in source)
            {
                sum += selector(v);
            }

            return (float)sum;
        }

        /// <summary>
        ///  Adds a sequence of values.
        /// </summary>
        /// <param name="source">The sequence to add.</param>
        /// <returns>The sum of the sequence.</returns>
        public static double SumF(this Span<double> source)
        {
            if (source == null)
            {
                throw Error.ArgumentNull("source");
            }
            double sum = 0;
            foreach (var v in source)
            {
                sum += v;
            }

            return sum;
        }

        /// <summary>
        /// Adds the transformed sequence of elements.
        /// </summary>
        /// <param name="source">The sequence of values to transform then sum.</param>
        /// <param name="selector">A transformation function.</param>
        /// <returns>The sum of the transformed elements.</returns>
        public static double SumF<T>(this Span<T> source, Func<T, double> selector)
        {
            if (source == null)
            {
                throw Error.ArgumentNull("source");
            }

            if (selector == null)
            {
                throw Error.ArgumentNull("selector");
            }

            double sum = 0;
            foreach (var v in source)
            {
                sum += selector(v);
            }

            return sum;
        }

        /// <summary>
        ///  Adds a sequence of values.
        /// </summary>
        /// <param name="source">The sequence to add.</param>
        /// <returns>The sum of the sequence.</returns>
        public static decimal SumF(this Span<decimal> source)
        {
            if (source == null)
            {
                throw Error.ArgumentNull("source");
            }
            decimal sum = 0;

            foreach (var v in source)
            {
                sum += v;
            }

            return sum;
        }

        /// <summary>
        /// Adds the transformed sequence of elements.
        /// </summary>
        /// <param name="source">The sequence of values to transform then sum.</param>
        /// <param name="selector">A transformation function.</param>
        /// <returns>The sum of the transformed elements.</returns>
        public static decimal SumF<T>(this Span<T> source, Func<T, decimal> selector)
        {
            if (source == null)
            {
                throw Error.ArgumentNull("source");
            }

            if (selector == null)
            {
                throw Error.ArgumentNull("selector");
            }

            decimal sum = 0;
            foreach (var v in source)
            {
                sum += selector(v);
            }

            return sum;
        }

        // --------------------------  LISTS  --------------------------------------------

        /// <summary>
        ///  Adds a sequence of values.
        /// </summary>
        /// <param name="source">The sequence to add.</param>
        /// <returns>The sum of the sequence.</returns>
        public static int SumF(this List<int> source)
        {
            if (source == null)
            {
                throw Error.ArgumentNull("source");
            }
            int sum = 0;
            checked
            {
                for (int i = 0; i < source.Count; i++)
                {
                    sum += source[i];
                }
            }
            return sum;
        }

        /// <summary>
        /// Adds the transformed sequence of elements.
        /// </summary>
        /// <param name="source">The sequence of values to transform then sum.</param>
        /// <param name="selector">A transformation function.</param>
        /// <returns>The sum of the transformed elements.</returns>
        public static int SumF<T>(this List<T> source, Func<T, int> selector)
        {
            if (source == null)
            {
                throw Error.ArgumentNull("source");
            }

            if (selector == null)
            {
                throw Error.ArgumentNull("selector");
            }

            int sum = 0;
            checked
            {
                for (int i = 0; i < source.Count; i++)
                {
                    sum += selector(source[i]);
                }
            }
            return sum;
        }

        /// <summary>
        ///  Adds a sequence of values.
        /// </summary>
        /// <param name="source">The sequence to add.</param>
        /// <returns>The sum of the sequence.</returns>
        public static long SumF(this List<long> source)
        {
            if (source == null)
            {
                throw Error.ArgumentNull("source");
            }
            long sum = 0;
            checked
            {
                for (int i = 0; i < source.Count; i++)
                {
                    sum += source[i];
                }
            }
            return sum;
        }

        /// <summary>
        /// Adds the transformed sequence of elements.
        /// </summary>
        /// <param name="source">The sequence of values to transform then sum.</param>
        /// <param name="selector">A transformation function.</param>
        /// <returns>The sum of the transformed elements.</returns>
        public static long SumF<T>(this List<T> source, Func<T, long> selector)
        {
            if (source == null)
            {
                throw Error.ArgumentNull("source");
            }

            if (selector == null)
            {
                throw Error.ArgumentNull("selector");
            }

            long sum = 0;
            checked
            {
                for (int i = 0; i < source.Count; i++)
                {
                    sum += selector(source[i]);
                }
            }
            return sum;
        }

        /// <summary>
        ///  Adds a sequence of values.
        /// </summary>
        /// <param name="source">The sequence to add.</param>
        /// <returns>The sum of the sequence.</returns>
        public static float SumF(this List<float> source)
        {
            if (source == null)
            {
                throw Error.ArgumentNull("source");
            }
            double sum = 0;

            for (int i = 0; i < source.Count; i++)
            {
                sum += source[i];
            }

            return (float)sum;
        }

        /// <summary>
        /// Adds the transformed sequence of elements.
        /// </summary>
        /// <param name="source">The sequence of values to transform then sum.</param>
        /// <param name="selector">A transformation function.</param>
        /// <returns>The sum of the transformed elements.</returns>
        public static float SumF<T>(this List<T> source, Func<T, float> selector)
        {
            if (source == null)
            {
                throw Error.ArgumentNull("source");
            }

            if (selector == null)
            {
                throw Error.ArgumentNull("selector");
            }

            double sum = 0;
            for (int i = 0; i < source.Count; i++)
            {
                sum += selector(source[i]);
            }

            return (float)sum;
        }

        /// <summary>
        ///  Adds a sequence of values.
        /// </summary>
        /// <param name="source">The sequence to add.</param>
        /// <returns>The sum of the sequence.</returns>
        public static double SumF(this List<double> source)
        {
            if (source == null)
            {
                throw Error.ArgumentNull("source");
            }
            double sum = 0;
            for (int i = 0; i < source.Count; i++)
            {
                sum += source[i];
            }

            return sum;
        }

        /// <summary>
        /// Adds the transformed sequence of elements.
        /// </summary>
        /// <param name="source">The sequence of values to transform then sum.</param>
        /// <param name="selector">A transformation function.</param>
        /// <returns>The sum of the transformed elements.</returns>
        public static double SumF<T>(this List<T> source, Func<T, double> selector)
        {
            if (source == null)
            {
                throw Error.ArgumentNull("source");
            }

            if (selector == null)
            {
                throw Error.ArgumentNull("selector");
            }

            double sum = 0;
            for (int i = 0; i < source.Count; i++)
            {
                sum += selector(source[i]);
            }

            return sum;
        }

        /// <summary>
        ///  Adds a sequence of values.
        /// </summary>
        /// <param name="source">The sequence to add.</param>
        /// <returns>The sum of the sequence.</returns>
        public static decimal SumF(this List<decimal> source)
        {
            if (source == null)
            {
                throw Error.ArgumentNull("source");
            }
            decimal sum = 0;

            for (int i = 0; i < source.Count; i++)
            {
                sum += source[i];
            }

            return sum;
        }

        /// <summary>
        /// Adds the transformed sequence of elements.
        /// </summary>
        /// <param name="source">The sequence of values to transform then sum.</param>
        /// <param name="selector">A transformation function.</param>
        /// <returns>The sum of the transformed elements.</returns>
        public static decimal SumF<T>(this List<T> source, Func<T, decimal> selector)
        {
            if (source == null)
            {
                throw Error.ArgumentNull("source");
            }

            if (selector == null)
            {
                throw Error.ArgumentNull("selector");
            }

            decimal sum = 0;
            for (int i = 0; i < source.Count; i++)
            {
                sum += selector(source[i]);
            }

            return sum;
        }

    }
}


text:
import ast
import os
import stat
import threading
import psycopg2
import psycopg2.extras
from psycopg2.extensions import ISOLATION_LEVEL_AUTOCOMMIT
from openpds.core.models import Profile
from openpds.backends.base import InternalDataStore
from openpds.backends.sql import dict_factory, getColumnDefForTable, getCreateStatementForTable, ListWithCount, getColumnValueFromRawData, SQLInternalDataStore
from openpds import settings

def getInternalDataStore(profile, app_id, lab_id, token):
    return PostgresInternalDataStore(profile, app_id, lab_id, token)

class PostgresInternalDataStore(SQLInternalDataStore):
    INITIALIZED_DATASTORES = []

    def __init__(self, profile, app_id, lab_id, token):
        super(PostgresInternalDataStore, self).__init__(profile, app_id, lab_id, token)

        self.profile = profile
        self.token = token
        self.source = "sql"

        if profile not in PostgresInternalDataStore.INITIALIZED_DATASTORES:
            PostgresInternalDataStore.INITIALIZED_DATASTORES.append(profile)
            try:
                init_conn = psycopg2.connect(user=settings.STORAGE_BACKEND["USER"], password=settings.STORAGE_BACKEND["PASSWORD"], database=profile.getDBName().lower())
            except psycopg2.OperationalError:
                init_conn = psycopg2.connect(user=settings.STORAGE_BACKEND["USER"], password=settings.STORAGE_BACKEND["PASSWORD"])
                init_conn.set_isolation_level(ISOLATION_LEVEL_AUTOCOMMIT)
                init_cur = init_conn.cursor()
                init_cur.execute("create database %s;"%profile.getDBName())
                init_cur.close()
                init_conn.close()
                init_conn = psycopg2.connect(user=settings.STORAGE_BACKEND["USER"], password=settings.STORAGE_BACKEND["PASSWORD"], database=profile.getDBName().lower())

            init_cur = init_conn.cursor()
            # We probably don't want to run the table creation every time (even if we're checking for existence).
            # Make this a setup / initialization method that we run once when a PDS is set up
            for table in SQLInternalDataStore.DATA_TABLE_LIST:
                if next((c for c in table["columns"] if c[0] == "time"), None) is None:
                    table["columns"].append(("time", "DOUBLE PRECISION PRIMARY KEY"))
                createStatement = getCreateStatementForTable(table)
                init_cur.execute(createStatement)

            for table in SQLInternalDataStore.ANSWER_TABLE_LIST:
                init_cur.execute(getCreateStatementForTable(table))
            init_conn.commit()
            init_cur.close()
            init_conn.close()
        self.db = psycopg2.connect(user=settings.STORAGE_BACKEND["USER"], password=settings.STORAGE_BACKEND["PASSWORD"], database=profile.getDBName().lower())

    def getCursor(self):
        return self.db.cursor(cursor_factory=psycopg2.extras.DictCursor)

    def getVariablePlaceholder(self):
        return "%s"


text:
这是一个把 `Alamofire` 请求的数据 转成 `SwiftyJSON` 中的 `JSON` 或者转化成`对象`

### 安装方法(Installation)

你可以通过`CocoaPods` 来使用`RxSwift-SwiftyJSON` 在你的Podfile中添加如下配置

RxSwift-SwiftyJSON is available through CocoaPods. To install it, simply add the following line to your Podfile:

```
pod 'RxSwift-SwiftyJSON', '~> 1.1'
```

然后运行`pod install`

### 使用方法(Usage)

创建一个实现 `ZJSwiftyJSONAble` 协议的`Class` 或者 `Struct`

Create a `Class` or `Struct` which implements the `ZJSwiftyJSONAble` protocol.

如果你返回数据的格式为:

if you get the json like this:

```json
{
    "success":"true",
    "msg":"获取用户信息成功",
    "obj":[]
}
```

你可以建立以下两个对象:

you can create two model like this:

```swift
import Foundation
import SwiftyJSON

class ZJResult_S<T: ZJSwiftyJSONAble>: ZJSwiftyJSONAble {
    var success: String!
    var msg: String!
    var obj: [T]?

    required init?(jsonData:JSON){
        self.success = jsonData["success"].stringValue
        self.msg = jsonData["msg"].stringValue
        self.obj = jsonData["obj"].arrayValue.flatMap { T(jsonData: $0) }
    }
}
```

```swift
import Foundation
import SwiftyJSON

class ZJArticle_S: ZJSwiftyJSONAble {
    var title: String!
    var keywords: String!
    var description: String!
    var date: String!
    var path: String!
    var url: String!

    required init?(jsonData:JSON){
        self.title = jsonData["title"].stringValue
        self.keywords = jsonData["keywords"].stringValue
        self.description = jsonData["description"].stringValue
        self.date = jsonData["date"].stringValue
        self.path = jsonData["path"].stringValue
        self.url = jsonData["url"].stringValue
    }
}
```

添加pod库

add pod

```
pod 'RxAlamofire'
```

然后我们就可以这样请求数据了

then we can query data like this:

```swift
_ = string(.POST, "http://t.yidaisong.com:90/login!in.do",
    parameters: ["userPhone":"15225178360","userLoginPswd":"123456"])
    .observeOn(MainScheduler.instance)
    .mapSwiftyObject(ZJResult_S<ZJUser_S>)
    .subscribe(
        onNext: { repos -> Void in
            self.showTextView.text = "用SwiftyJSON把结果转为对象\n"
                                   + "用户名:\(repos.obj!.userName)\n"
                                   + "昵称:\(repos.obj!.userAlias)";
        },
        onError: { (error) -> Void in
            self.showTextView.text = "\(error)";
    })
```

是不是很简单

so easy

如果你不想转为对象 想直接用 SwiftyJSON 对应的JSON格式  你可以这样写

if you dont want to change it to model,just to JSON,you can write like this

```swift
_ = string(.POST, "http://t.yidaisong.com:90/login!in.do",
    parameters: ["userPhone":"15225178360","userLoginPswd":"123456"])
    .observeOn(MainScheduler.instance)
    .mapSwiftyJSON()
    .subscribe(
        onNext: { repos -> Void in
            self.showTextView.text = "用SwiftyJSON把结果转为JSON\n"
                                   + "用户名:\(repos["obj"]["userName"].stringValue)\n"
                                   + "昵称:\(repos["obj"]["userAlias"].stringValue)";
        },
        onError: { (error) -> Void in
            self.showTextView.text = "\(error)";
    })
```

## 作者(Author)

剑行者

+ 网站: [www.psvmc.cn](http://www.psvmc.cn)
+ 邮箱: [183518918@qq.com](mailto:183518918@qq.com)

## 版权(License)

你可以在MIT许可下使用`RxSwift-SwiftyJSON`,更多信息请查看`LICENSE`文件

`RxSwift-SwiftyJSON` is available under the MIT license. See the LICENSE file for more info.


text:
package fr.adrienbrault.idea.symfony2plugin.navigation;

import com.intellij.lang.Language;
import com.intellij.lang.html.HTMLLanguage;
import com.intellij.navigation.GotoRelatedItem;
import com.intellij.navigation.GotoRelatedProvider;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.patterns.PlatformPatterns;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.psi.util.PsiTreeUtil;
import com.jetbrains.twig.TwigFile;
import com.jetbrains.twig.TwigLanguage;
import com.jetbrains.twig.elements.TwigBlockStatement;
import com.jetbrains.twig.elements.TwigBlockTag;
import com.jetbrains.twig.elements.TwigElementTypes;
import com.jetbrains.twig.elements.TwigTagWithFileReference;
import fr.adrienbrault.idea.symfony2plugin.Symfony2Icons;
import fr.adrienbrault.idea.symfony2plugin.Symfony2ProjectComponent;
import fr.adrienbrault.idea.symfony2plugin.dic.RelatedPopupGotoLineMarker;
import fr.adrienbrault.idea.symfony2plugin.templating.TwigPattern;
import fr.adrienbrault.idea.symfony2plugin.templating.util.TwigUtil;
import fr.adrienbrault.idea.symfony2plugin.twig.utils.TwigBlockUtil;
import fr.adrienbrault.idea.symfony2plugin.util.PsiElementUtils;
import icons.TwigIcons;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @author Daniel Espendiller <daniel@espendiller.net>
 */
public class TwigGotoRelatedProvider extends GotoRelatedProvider {
    @NotNull
    @Override
    public List<? extends GotoRelatedItem> getItems(@NotNull PsiElement psiElement2) {
        if (!Symfony2ProjectComponent.isEnabled(psiElement2)) {
            return Collections.emptyList();
        }

        Language language = psiElement2.getLanguage();
        if (language != TwigLanguage.INSTANCE && language != HTMLLanguage.INSTANCE) {
            return Collections.emptyList();
        }

        List<GotoRelatedItem> gotoRelatedItems = new ArrayList<>();

        PsiElement psiElement = TwigUtil.getElementOnTwigViewProvider(psiElement2);
        if (psiElement == null) {
            return Collections.emptyList();
        }

        PsiFile psiFile = psiElement.getContainingFile();
        if (psiFile instanceof TwigFile) {
            // extends
            Set<String> templates = new HashSet<>();
            TwigUtil.visitTemplateExtends((TwigFile) psiFile, pair -> templates.add(pair.getFirst()));
            Set<VirtualFile> virtualFiles = new HashSet<>();
            for (String template : templates) {
                for (PsiFile templatePsiElement : TwigUtil.getTemplatePsiElements(psiElement.getProject(), template)) {
                    VirtualFile virtualFile = templatePsiElement.getVirtualFile();
                    if (!virtualFiles.contains(virtualFile)) {
                        virtualFiles.add(virtualFile);
                        gotoRelatedItems.add(new RelatedPopupGotoLineMarker.PopupGotoRelatedItem(templatePsiElement, "extends").withIcon(TwigIcons.TwigFileIcon, Symfony2Icons.TWIG_LINE_MARKER));
                    }
                }
            }

            // twig blocks up
            @Nullable TwigBlockStatement parentOfType = PsiTreeUtil.getParentOfType(psiElement, TwigBlockStatement.class);
            if (parentOfType != null) {
                TwigBlockTag twigBlockTag = PsiTreeUtil.findChildOfType(parentOfType, TwigBlockTag.class);
                if (twigBlockTag != null) {
                    PsiElement childrenOfType = PsiElementUtils.getChildrenOfType(twigBlockTag, TwigPattern.getBlockTagPattern());
                    if (childrenOfType != null) {
                        String blockName = twigBlockTag.getName();

                        gotoRelatedItems.addAll(TwigBlockUtil.getBlockOverwriteTargets(childrenOfType).stream().map((Function<PsiElement, GotoRelatedItem>) psiElement1 ->
                            new RelatedPopupGotoLineMarker.PopupGotoRelatedItem(psiElement1, blockName).withIcon(Symfony2Icons.TWIG_BLOCK_OVERWRITE, Symfony2Icons.TWIG_BLOCK_OVERWRITE)
                        ).collect(Collectors.toList()));

                        gotoRelatedItems.addAll(TwigBlockUtil.getBlockImplementationTargets(childrenOfType).stream().map((Function<PsiElement, GotoRelatedItem>) psiElement1 ->
                            new RelatedPopupGotoLineMarker.PopupGotoRelatedItem(psiElement1, blockName).withIcon(Symfony2Icons.TWIG_BLOCK_OVERWRITE, Symfony2Icons.TWIG_BLOCK_OVERWRITE)
                        ).collect(Collectors.toList()));
                    }
                }
            }

            // "include" and other file tags
            TwigTagWithFileReference twigTagWithFileReference = PsiTreeUtil.getParentOfType(psiElement, TwigTagWithFileReference.class);
            if (twigTagWithFileReference != null) {
                visitFileReferenceElement(psiElement.getProject(), gotoRelatedItems, twigTagWithFileReference);
            }

            // "embed" tag
            PsiElement parentOfType1 = PsiElementUtils.getParentOfType(psiElement, TwigElementTypes.EMBED_STATEMENT);
            if (parentOfType1 != null) {
                PsiElement embedTag = PsiElementUtils.getChildrenOfType(parentOfType1, PlatformPatterns.psiElement().withElementType(TwigElementTypes.EMBED_TAG));
                if (embedTag != null) {
                    visitFileReferenceElement(psiElement.getProject(), gotoRelatedItems, embedTag);
                }
            }
        }

        return gotoRelatedItems;
    }

    private void visitFileReferenceElement(@NotNull Project project, @NotNull List<GotoRelatedItem> gotoRelatedItems, @NotNull PsiElement psiElement) {
        TwigUtil.visitTemplateIncludes(psiElement, templateInclude -> {
            for (PsiFile templatePsiElement : TwigUtil.getTemplatePsiElements(project, templateInclude.getTemplateName())) {
                gotoRelatedItems.add(new RelatedPopupGotoLineMarker.PopupGotoRelatedItem(templatePsiElement, templateInclude.getType().toString().toLowerCase()).withIcon(Symfony2Icons.TWIG_BLOCK_OVERWRITE, Symfony2Icons.TWIG_BLOCK_OVERWRITE));
            }
        });
    }
}


text:
c -*- Fortran -*-
c
c~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
c
c  Lithomop3d by Charles A. Williams
c  Copyright (c) 2003-2005 Rensselaer Polytechnic Institute
c
c  Permission is hereby granted, free of charge, to any person obtaining
c  a copy of this software and associated documentation files (the
c  "Software"), to deal in the Software without restriction, including
c  without limitation the rights to use, copy, modify, merge, publish,
c  distribute, sublicense, and/or sell copies of the Software, and to
c  permit persons to whom the Software is furnished to do so, subject to
c  the following conditions:
c
c  The above copyright notice and this permission notice shall be
c  included in all copies or substantial portions of the Software.
c
c  THE  SOFTWARE IS  PROVIDED  "AS  IS", WITHOUT  WARRANTY  OF ANY  KIND,
c  EXPRESS OR  IMPLIED, INCLUDING  BUT NOT LIMITED  TO THE  WARRANTIES OF
c  MERCHANTABILITY,    FITNESS    FOR    A   PARTICULAR    PURPOSE    AND
c  NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
c  LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
c  OF CONTRACT, TORT OR OTHERWISE,  ARISING FROM, OUT OF OR IN CONNECTION
c  WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
c
c~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
c
c
      subroutine ldisbc(dl,bond,ien,lm,nen,numnp)
c
c...program to localize prescribed displacement boundary conditions
c   dl(ndof,nen) = element prescribed displacement boundary
c                         condition array
c
      include "implicit.inc"
c
c...  parameter definitions
c
      include "ndimens.inc"
      include "nconsts.inc"
      include "rconsts.inc"
c
c...  subroutine arguments
c
      integer nen,numnp
      integer ien(nen),lm(ndof,nen)
      double precision dl(ndof,nen),bond(ndof,numnp)
c
c...  local variables
c
      integer i,j,k
c
      call  fill(dl,zero,ndof*nen)
      do i=1,ndof
        do j=1,nen
          if(lm(i,j).eq.izero) then
            k=ien(j)
            dl(i,j)=bond(i,k)
          end if
        end do
      end do
      return
      end
c
c version
c $Id: ldisbc.f,v 1.2 2004/07/07 15:46:54 willic3 Exp $
c
c Generated automatically by Fortran77Mill on Wed May 21 14:15:03 2003
c
c End of file


text:
export const BasicParentActionTypes = {
	CHANGE_MESSAGE: "BASIC_PARENT.CHANGE_MESSAGE"
}

//api interface
export interface BasicParentActionApi {
	changeMessage?: { (message: string): void }
}

//creators
export function changeMessage(message: string) {
	return {
		type: BasicParentActionTypes.CHANGE_MESSAGE,
		message
	}
}


text:
Cactus.UnitTest.Web.Events = function () {
  var UT = Cactus.Dev.UnitTest;
  var Test = UT.Test;
  var Events = Cactus.Web.Events;
  var tag = Cactus.Web.tag;

  var tc = new UT.TestCase("Web.Events");
  tc.setup = function () {
    this.o = {};
    this.oFunc = function () { };
    new Events(this.o);
    this.o.events.add("click", this.oFunc);
  };

  // Create an events object.
  tc.add(function () {
    var o = this.o;
    this.assert(o.events instanceof Events);
    this.assert(o.onclick instanceof Function);
    this.assertEqual(o, o.events.element.events.element);
  });

  // Test adding single event function.
  tc.add(function () {
    var o = this.o;
    this.assert(o.events instanceof Events);
    this.assertEqual(1, o.events.events.onclick.length);
  });

  // Test Events.add.
  tc.add(function () {
    var o = {};
    Events.add(o, "click", this.oFunc);
    this.assertEqual(1, o.events.events.onclick.length);
  });

  // Events.add should throw an error if element argument is an array.
  tc.add(function () {
    this.assertException(Error,
                         Events.add.curry([], "click", Function.empty));
  });

  // Events.add should throw an error if callback argument isn't a function.
  tc.add(function () {
    this.assertException(Error,
                         Events.add.curry({}, "click", "not a function"));
  });

  // Test event execution.
  tc.add(function () {
    var o = {};
    var triggered = false;
    Events.add(o, "click", function () {
      triggered = true;
    });
      o.onclick();
    this.assert(triggered);
    // Add two more events.
    triggered = false;
    var triggeredB = false;
    var triggeredC = false;
    Events.add(o, "click", function () {
      triggeredB = true;
    });
      Events.add(o, "click", function () {
        triggeredC = true;
      });
    o.onclick();
    this.assert(triggered);
    this.assert(triggeredB);
    this.assert(triggeredC);
  });

  // Test event deletion.
  tc.add(function () {
    var o = {};
    var triggered;

    triggered = false;
    var eventID = Events.add(o, "click", function () {
      triggered = true;
    });
    o.onclick();
    this.assert(triggered, "event did not trigger");

    o.events.del("click", eventID);
      triggered = false;
    o.onclick();
    this.assertFalse(triggered, "event was not removed");

  });

  // Make sure adding different event types works properly.
  tc.add(function () {
    var o = {};
    var triggeredClick = false;
    var triggeredFoo = false;
    Events.add(o, "click", function () {
      triggeredClick = true;
    });
    Events.add(o, "foo", function () {
      triggeredFoo = true;
    });

    o.onclick();
    this.assert(triggeredClick);
    this.assertFalse(triggeredFoo);

    triggeredClick = false;
    o.onfoo();
    this.assert(triggeredFoo);
    this.assertFalse(triggeredClick);
  });

  // Test return value of event.
  tc.add(function () {
    var o = {};
    var f = Function.empty.returning(false);
    Events.add(o, "click", f);

    this.assertFalse(o.onclick());

    // Make sure that all added events are triggered.  for this to
    // work we have to make sure that g is executed before h, but
    // how do we do this when for in iterates in an arbitrary
    // order and we don't want to enforce ordering?
    var hTriggered = false;
    var lastTrigger = "";
    function g() {
      lastTrigger = "g";
      return false;
    }
    function h() {
      lastTrigger = "h";
      hTriggered = true;
    }
    Events.add(o, "foo", g);
    Events.add(o, "foo", h);
    this.assertFalse(o.onfoo(), "onfoo did not return false");
    this.assertEqual("h", lastTrigger);
    this.assert(hTriggered, "h did not trigger");
  });

  // Make sure the default scope is the element.
  tc.add(function () {
    var test = this;
    var o = {};
    var fooTriggered = false;
    Events.add(o, "foo", function () {
      fooTriggered = true;
      test.assertEqual(o, this);
    });

    o.onfoo();
    this.assert(fooTriggered, "onfoo did not trigger");
  });

  // Make sure adding events returns an ID that we can use to remove
  // the event.
  tc.add(function () {
    var o = {};
    var fooTriggered = false;
    var id = Events.add(o, "foo", function () {
        fooTriggered = true;
    });

    o.onfoo();
    this.assert(fooTriggered);

    fooTriggered = false;
    Events.del(o, "foo", id);
    o.onfoo();
    this.assertFalse(fooTriggered);
  });

  // Trying to remove a non-existing event should throw an error.
  tc.add(function () {
    var o = {};
    this.assertException(Error, function () {
      Events.del(o, "click", "foo");
      });
    });

  // Test behavior when cloning HTML elements.
  tc.add(function () {
    var d1 = tag("div");
    var aTriggered = false;
    var bTriggered = false;
    Events.add(d1, "click", function () {
      aTriggered = true;
    });
    var d2 = d1.cloneNode(true);
    Events.add(d2, "click", function () {
      bTriggered = true;
    });
    d1.onclick();
    this.assert(aTriggered, "A did not trigger.");
    this.assertFalse(bTriggered, "B triggered.");
    d2.onclick();
  });

  // If 3rd party code uses the same method for binding events, we should
  // play nice and not remove the event.
  tc.add(function () {
    var initialScope = null;
    var intialE = null;
      var initialTriggered = false;
    var f = function (e) {
      initialTriggered = true;
      initialScope = this;
      initialE = e;
    };
    var el = {
      onclick : f
    };

    var secondaryTriggered = false;
    Events.add(el,"click",function () {
      secondaryTriggered = true;
    });
    var myE = {};
    el.onclick(myE);
    this.assert(initialTriggered, "Initial event did not trigger.");
    this.assert(secondaryTriggered, "New event did not trigger.");
    this.assertEqual(el, initialScope);
    this.assertEqual(myE, initialE);
    });

  return tc;
};


text:
import unittest

from quadratic_primes import *

class TestQuadraticPrimes(unittest.TestCase):
    def test_quadratic_primes(self):
        self.assertEqual(quadratic_primes(3), (-1, 2))
        self.assertEqual(quadratic_primes(5), (-2, 3))
        self.assertEqual(quadratic_primes(10), (-3, 7))
        self.assertEqual(quadratic_primes(42), (-1, 41))
        self.assertEqual(quadratic_primes(100), (-15, 97))
        self.assertEqual(quadratic_primes(200), (-25, 197))
        self.assertEqual(quadratic_primes(300), (-31, 281))

    def test_project_euler_input(self):
        result = quadratic_primes(1000)
        self.assertEqual(result, (-61, 971))
        self.assertEqual(result[0] * result[1], -59231)

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


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

namespace LightRail
{
    public class IncomingTransportMessage
    {
        public IncomingTransportMessage(string messageId, Dictionary<string, string> headers, string serializedMessagedata)
        {
            MessageId = messageId;
            Headers = headers;
            Headers[StandardHeaders.MessageId] = messageId;
            SerializedMessageData = serializedMessagedata;
        }

        public string MessageId { get; private set; }
        public Dictionary<string, string> Headers { get; private set; }
        public string SerializedMessageData { get; private set; }
    }
}


text:
//===--- RemoteAST.h - Relating remote metadata to local ASTs ---*- C++ -*-===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
//  The RemoteAST library defines interfaces for exploring the
//  relationships between a remote process and a local AST which provides
//  a (static and incomplete) picture of the code running in that process.
//
//===----------------------------------------------------------------------===//

#ifndef SWIFT_REMOTEAST_REMOTEAST_H
#define SWIFT_REMOTEAST_REMOTEAST_H

#include "swift/Remote/Failure.h"
#include "swift/Remote/MemoryReader.h"
#include "swift/Basic/LLVM.h"
#include "swift/ABI/MetadataValues.h"
#include "swift/AST/Type.h"
#include "llvm/ADT/StringRef.h"

#include <memory>

namespace swift {
class ASTContext;
class NominalTypeDecl;

namespace remoteAST {

template <class T>
class Result {
  union Storage {
    remote::Failure Failure;
    T Success;

    Storage() {}
    Storage(const Storage &) = delete;
    Storage &operator=(const Storage &) = delete;
    ~Storage() {}
  };

  Storage S;
  bool IsSuccess;

  Result(bool isSuccess) : IsSuccess(isSuccess) {}

public:
  /*implicit*/ Result(const T &value) : IsSuccess(true) {
    new (&S.Success) T(value);
  }

  /*implicit*/ Result(T &&value) : IsSuccess(true) {
    new (&S.Success) T(std::move(value));
  }

  /*implicit*/ Result(remote::Failure &&failure) : IsSuccess(false) {
    new (&S.Failure) remote::Failure(std::move(failure));
  }

  Result(const Result &other) : IsSuccess(other.IsSuccess) {
    if (IsSuccess) {
      ::new (&S.Success) T(other.S.Success);
    } else {
      ::new (&S.Failure) remote::Failure(other.S.Failure);
    }
  }

  Result(Result &&other) : IsSuccess(other.IsSuccess) {
    if (IsSuccess) {
      ::new (&S.Success) T(std::move(other.S.Success));
    } else {
      ::new (&S.Failure) remote::Failure(std::move(other.S.Failure));
    }
  }

  Result &operator=(const Result &other) {
    this->~Result();
    ::new (this) Result(other);
    return *this;
  }

  Result &operator=(Result &&other) {
    this->~Result();
    ::new (this) Result(std::move(other));
    return *this;
  }

  ~Result() {
    if (IsSuccess) {
      S.Success.~T();
    } else {
      S.Failure.~Failure();
    }
  }

  template <class... ArgTys>
  static Result emplaceSuccess(ArgTys &&...args) {
    Result result(true);
    ::new (&result.S.Success) T(std::forward<ArgTys>(args)...);
    return result;
  }

  template <class KindTy, class... ArgTys>
  static Result emplaceFailure(KindTy kind, ArgTys &&...args) {
    Result result(false);
    ::new (&result.S.Failure)
      remote::Failure(kind, std::forward<ArgTys>(args)...);
    return result;
  }

  explicit operator bool() const { return isSuccess(); }
  bool isSuccess() const { return IsSuccess; }
  bool isFailure() const { return !IsSuccess; }

  const remote::Failure &getFailure() const {
    assert(isFailure());
    return S.Failure;
  }

  const T &getValue() const & {
    assert(isSuccess());
    return S.Success;
  }

  T &&getValue() && {
    assert(isSuccess());
    return std::move(S.Success);
  }
};

/// A structure representing an opened existential value.
struct OpenedExistential {
  /// The concrete type of the value inside the existential.
  Type InstanceType;

  /// The address of the payload.
  ///
  /// Note: If the concrete type is a class type, this is the address of the
  /// instance and not the address of the reference to the instance.
  remote::RemoteAddress PayloadAddress;

  OpenedExistential(Type InstanceType, remote::RemoteAddress PayloadAddress)
      : InstanceType(InstanceType), PayloadAddress(PayloadAddress) {}
};

/// A context for performing an operation relating the remote process with
/// the AST.  This may be discarded and recreated at any time without danger,
/// but reusing a context across multiple calls may allow some redundant work
/// to be avoided.
///
/// The operations on this type must not assert or crash for any of the
/// following reasons:
///   - the parameters do not satisfy preconditions
///   - the memory reader fails for any reason
///   - the remote address is invalid
///   - the remote address space is corrupt
///   - the remote address space contains valid-seeming constructs that
///     somehow violate local well-formedness rules
///   - the local AST does not contain information for the remote construct
///
/// The operations on this type *may* misbehave if the invariants of
/// the local AST have been violated.  This should not be a problem if the
/// local AST is the result of ordinary type-checking.
class RemoteASTContext {
  void *Impl;

public:
  explicit RemoteASTContext(ASTContext &ctx,
                            std::shared_ptr<remote::MemoryReader> reader);

  RemoteASTContext(const RemoteASTContext &) = delete;
  RemoteASTContext &operator=(const RemoteASTContext &) = delete;

  ~RemoteASTContext();

  /// Given an address which is supposedly of type metadata, try to
  /// resolve it to a specific type in the local AST.
  ///
  /// \param skipArtificial If true, the address may be an artificial type
  ///   wrapper that should be ignored. For example, it could be a
  ///   dynamic subclass created by (e.g.) CoreData or KVO; if so, and this
  ///   flag is set, this method will implicitly ignore the subclass
  ///   and instead attempt to resolve a type for the first non-artificial
  ///   superclass. See [NOTE: Dynamic-subclass-KVO].
  Result<Type>
  getTypeForRemoteTypeMetadata(remote::RemoteAddress address,
                               bool skipArtificial = false);

  /// Given an address which is supposedly of type metadata, try to
  /// resolve it to a specific MetadataKind value for its backing type.
  Result<MetadataKind>
  getKindForRemoteTypeMetadata(remote::RemoteAddress address);

  /// Given an address which is supposedly of a nominal type descriptor,
  /// try to resolve it to a specific nominal type declaration in the
  /// local AST.
  Result<NominalTypeDecl *>
  getDeclForRemoteNominalTypeDescriptor(remote::RemoteAddress address);

  /// Given a type in the local AST, try to resolve the offset of its
  /// member with the given name.  This supports:
  ///
  ///   - stored properties of structs
  ///   - stored properties of classes
  ///   - elements of tuples
  ///
  /// Failure may indicate that an offset for the property could not be
  /// resolved, or it may simply indicate that the property is not laid
  /// out at a known offset.
  ///
  /// If the caller has the address of type metadata for the type, it may
  /// pass it in; this may allow the implementation to compute an offset in
  /// situations where it otherwise cannot.
  Result<uint64_t> getOffsetOfMember(Type type,
                                     remote::RemoteAddress optMetadataAddress,
                                     StringRef memberName);

  /// Given a heap object, resolve its heap metadata.
  Result<remote::RemoteAddress>
  getHeapMetadataForObject(remote::RemoteAddress address);

  /// Resolve the dynamic type and the value address of an error existential
  /// object, Unlike getDynamicTypeAndAddressForExistential(), this function
  /// takes the address of the instance and not the address of the reference.
  Result<OpenedExistential>
  getDynamicTypeAndAddressForError(remote::RemoteAddress object);

  /// Given an existential and its static type, resolve its dynamic
  /// type and address. A single step of unwrapping is performed, i.e. if the
  /// value stored inside the existential is itself an existential, the
  /// caller can decide whether to iterate itself.
  Result<OpenedExistential>
  getDynamicTypeAndAddressForExistential(remote::RemoteAddress address,
                                         Type staticType);

  /// Given a reference to an opaque type descriptor, an ordinal, and a set
  /// of substitutions, get the underlying type for the opaque type.
  ///
  /// This does not recursively apply the transformation if the underlying
  /// type in turn refers to another opaque type.
  Result<Type>
  getUnderlyingTypeForOpaqueType(remote::RemoteAddress opaqueDescriptor,
                                 SubstitutionMap substitutions,
                                 unsigned ordinal);

};

} // end namespace remoteAST
} // end namespace swift

#endif // SWIFT_REMOTEAST_REMOTEAST_H


text:
i = 5
print i
i = i + 1
print i
s = '''This is a multi-line string.
This is the second line.'''

print s


text:
export default standingsCalculator;

function standingsCalculator(division) {
  let teams = division.teams;
  let rounds = division.rounds;
  let standings = [];
  let standingsById = {};

  teams.forEach(team => {
    let standing = {
      team: team,
      get points() {
        return 3 * this.matchesWon + this.matchesDrawn;
      },
      get matchesPlayed() {
        return this.matchesWon + this.matchesDrawn + this.matchesLost;
      },
      matchesWon: 0,
      matchesDrawn: 0,
      matchesLost: 0,
      goalsScored: 0,
      goalsAgainst: 0,
      get goalsDifference() {
        return this.goalsScored - this.goalsAgainst;
      },
      yellowCards: 0,
      redCards: 0,
      generatedYellowCards: 0,
      generatedRedCards: 0,
      get totalYellowCardsOnMatches() {
        return this.yellowCards + this.generatedYellowCards;
      },
      get totalRedCardsOnMatches() {
        return this.redCards + this.generatedRedCards;
      }
    };
    standings.push(standing);
    standingsById[team.id] = standing;
  });

  rounds.forEach(round => {
    round.matches.forEach(match => {
      if (!match.hasResults) {
        return;
      }

      let localStanding = standingsById[match.localStats.team.id];
      let visitorStanding = standingsById[match.visitorStats.team.id];
      let diffGoals = match.visitorStats.goals.length - match.localStats.goals.length;

      if (diffGoals < 0) {
        localStanding.matchesWon++;
        visitorStanding.matchesLost++;
      } else if (diffGoals > 0) {
        visitorStanding.matchesWon++;
        localStanding.matchesLost++;
      } else {
        localStanding.matchesDrawn++;
        visitorStanding.matchesDrawn++;
      }

      countGoalsAndCards(localStanding, match.localStats, match.visitorStats);
      countGoalsAndCards(visitorStanding, match.visitorStats, match.localStats);
    });
  });

  standings.sort(standingSorter);

  return standings;
}

function standingSorter(leftStanding, rightStanding) {
  let diffPoints = rightStanding.points - leftStanding.points;

  if (diffPoints !== 0) {
    return diffPoints;
  }

  let diffGoalsDifference =
      rightStanding.goalsScored - rightStanding.goalsAgainst -
      (leftStanding.goalsScored - leftStanding.goalsAgainst);

  if (diffGoalsDifference !== 0) {
    return diffGoalsDifference;
  }

  let diffGoalsScored = rightStanding.goalsScored - leftStanding.goalsScored;

  return diffGoalsScored;
}

function countGoalsAndCards(standing, teamStats, opponentTeamStats) {
  standing.goalsScored += teamStats.goals.length;
  standing.goalsAgainst += opponentTeamStats.goals.length;

  teamStats.cards.forEach(card => {
    if (card.type === 'yellow') {
      standing.yellowCards += 1;
    } else if (card.type === 'red') {
      standing.redCards += 1;
    }
  });

  opponentTeamStats.cards.forEach(card => {
    if (card.type === 'yellow') {
      standing.generatedYellowCards += 1;
    } else if (card.type === 'red') {
      standing.generatedRedCards += 1;
    }
  });
}


text:
title: Array.prototype.filter
localeTitle: Array.prototype.filter
---
## Array.prototype.filter

O método de filtro usa um array como entrada. Leva cada elemento na matriz e aplica uma instrução condicional contra ele. Se esta condição retornar true, o elemento será "empurrado" para a matriz de saída.

Uma vez que cada elemento na matriz de entrada é "filtrado" como tal, gera uma nova matriz contendo cada elemento que retornou verdadeiro.

Neste exemplo abaixo, há uma matriz que possui vários objetos dentro dela. Normalmente, para percorrer esse array, você pode usar um loop for.

Nesse caso, queremos que todos os alunos cujas notas sejam maiores ou iguais a 90.

```javascript
var students = [
  { name: 'Quincy', grade: 96 },
  { name: 'Jason', grade: 84 },
  { name: 'Alexis', grade: 100 },
  { name: 'Sam', grade: 65 },
  { name: 'Katie', grade: 90 }
 ];
 //Define an array to push student objects to.
 var studentsGrades = []
 for (var i = 0; i < students.length; i++) {
  //Check if grade is greater than 90
  if (students[i].grade >= 90) {
    //Add a student to the studentsGrades array.
    studentsGrades.push(students[i])
  }
 }

 return studentsGrades; // [ { name: 'Quincy', grade: 96 }, { name: 'Alexis', grade: 100 }, { name: 'Katie', grade: 90 } ]
```

Esse loop funciona, mas é bem demorado. Também pode tornar-se tedioso escrever repetidamente loops para muitos arrays que você precisa percorrer.

Este é um ótimo caso de uso para filtro!

Aqui está o mesmo exemplo usando o filtro:

```javascript
var students = [
  { name: 'Quincy', grade: 96 },
  { name: 'Jason', grade: 84 },
  { name: 'Alexis', grade: 100 },
  { name: 'Sam', grade: 65 },
  { name: 'Katie', grade: 90 }
 ];

 var studentGrades = students.filter(function (student) {
  //This tests if student.grade is greater than or equal to 90. It returns the "student" object if this conditional is met.
  return student.grade >= 90;
 });

 return studentGrades; // [ { name: 'Quincy', grade: 96 }, { name: 'Alexis', grade: 100 }, { name: 'Katie', grade: 90 } ]
```

O método de filtro é muito mais rápido de escrever e mais limpo de ler enquanto ainda realiza a mesma coisa. Usando a sintaxe do ES6, podemos até replicar o loop for de 6 linhas com filtro:

```javascript
var students = [
  { name: 'Quincy', grade: 96 },
  { name: 'Jason', grade: 84 },
  { name: 'Alexis', grade: 100 },
  { name: 'Sam', grade: 65 },
  { name: 'Katie', grade: 90 }
 ];

 var studentGrades = students.filter(student => student.grade >= 90);
 return studentGrades; // [ { name: 'Quincy', grade: 96 }, { name: 'Alexis', grade: 100 }, { name: 'Katie', grade: 90 } ]
```

O filtro é muito útil e é uma excelente opção em loops forçados para filtrar matrizes contra instruções condicionais.

#### Mais Informações:

[MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter)


text:
package sqlbase

import "github.com/cockroachdb/cockroach/sql/parser"

// RunFilter runs a filter expression and returns whether the filter passes.
func RunFilter(filter parser.TypedExpr, evalCtx *parser.EvalContext) (bool, error) {
	if filter == nil {
		return true, nil
	}

	d, err := filter.Eval(evalCtx)
	if err != nil {
		return false, err
	}

	return d != parser.DNull && bool(*d.(*parser.DBool)), nil
}


text:
"""
/hosts endpoint for Daisy v1 API
"""
import subprocess
from oslo_config import cfg
from oslo_log import log as logging
from webob.exc import HTTPBadRequest
from webob.exc import HTTPConflict
from webob.exc import HTTPForbidden
from webob.exc import HTTPNotFound
from webob import Response
from collections import Counter
from webob.exc import HTTPServerError
from daisy.api import policy
import daisy.api.v1
from daisy.api.v1 import controller
from daisy.api.v1 import filters
from daisy.common import exception
from daisy.common import property_utils
from daisy.common import utils
from daisy.common import wsgi
from daisy import i18n
from daisy import notifier
import daisy.registry.client.v1.api as registry

LOG = logging.getLogger(__name__)
_ = i18n._
_LE = i18n._LE
_LI = i18n._LI
_LW = i18n._LW
SUPPORTED_PARAMS = daisy.api.v1.SUPPORTED_PARAMS
SUPPORTED_FILTERS = daisy.api.v1.SUPPORTED_FILTERS
ACTIVE_IMMUTABLE = daisy.api.v1.ACTIVE_IMMUTABLE

CONF = cfg.CONF
CONF.import_opt('disk_formats', 'daisy.common.config', group='image_format')
CONF.import_opt('container_formats', 'daisy.common.config',
                group='image_format')
CONF.import_opt('image_property_quota', 'daisy.common.config')

class Controller(controller.BaseController):
    """
    WSGI controller for hosts resource in Daisy v1 API

    The hosts resource API is a RESTful web service for host data. The API
    is as follows::

        GET  /nodes -- Returns a set of brief metadata about hosts
        GET  /nodes -- Returns a set of detailed metadata about
                              hosts
        HEAD /nodes/<ID> -- Return metadata about an host with id <ID>
        GET  /nodes/<ID> -- Return host data for host with id <ID>
        POST /nodes -- Store host data and return metadata about the
                        newly-stored host
        PUT  /nodes/<ID> -- Update host metadata and/or upload host
                            data for a previously-reserved host
        DELETE /nodes/<ID> -- Delete the host with id <ID>
    """
    support_resource_type = ['baremetal', 'server', 'docker']

    def __init__(self):
        self.notifier = notifier.Notifier()
        registry.configure_registry_client()
        self.policy = policy.Enforcer()
        if property_utils.is_property_protection_enabled():
            self.prop_enforcer = property_utils.PropertyRules(self.policy)
        else:
            self.prop_enforcer = None

    def _enforce(self, req, action, target=None):
        """Authorize an action against our policies"""
        if target is None:
            target = {}
        try:
            self.policy.enforce(req.context, action, target)
        except exception.Forbidden:
            raise HTTPForbidden()

    def _raise_404_if_network_deleted(self, req, network_id):
        network = self.get_network_meta_or_404(req, network_id)
        if network is None or network['deleted']:
            msg = _("Network with identifier %s has been deleted.") % network_id
            raise HTTPNotFound(msg)

    def _raise_404_if_cluster_deleted(self, req, cluster_id):
        cluster = self.get_cluster_meta_or_404(req, cluster_id)
        if cluster is None or cluster['deleted']:
            msg = _("Cluster with identifier %s has been deleted.") % cluster_id
            raise HTTPNotFound(msg)

    def _raise_404_if_role_deleted(self, req, role_id):
        role = self.get_role_meta_or_404(req, role_id)
        if role is None or role['deleted']:
            msg = _("Cluster with identifier %s has been deleted.") % role_id
            raise HTTPNotFound(msg)

    def _get_filters(self, req):
        """
        Return a dictionary of query param filters from the request

        :param req: the Request object coming from the wsgi layer
        :retval a dict of key/value filters
        """
        query_filters = {}
        for param in req.params:
            if param in SUPPORTED_FILTERS:
                query_filters[param] = req.params.get(param)
                if not filters.validate(param, query_filters[param]):
                    raise HTTPBadRequest(_('Bad value passed to filter '
                                           '%(filter)s got %(val)s')
                                         % {'filter': param,
                                            'val': query_filters[param]})
        return query_filters

    def _get_query_params(self, req):
        """
        Extracts necessary query params from request.

        :param req: the WSGI Request object
        :retval dict of parameters that can be used by registry client
        """
        params = {'filters': self._get_filters(req)}

        for PARAM in SUPPORTED_PARAMS:
            if PARAM in req.params:
                params[PARAM] = req.params.get(PARAM)
        return params

    @utils.mutating
    def add_host(self, req, host_meta):
        """
        Adds a new host to Daisy

        :param req: The WSGI/Webob Request object
        :param image_meta: Mapping of metadata about host

        :raises HTTPBadRequest if x-host-name is missing
        """
        # if host is update in '_verify_interface_among_hosts', no need add host continue.
        cluster_id = host_meta.get('cluster', None)
        if self._verify_interface_among_hosts(req, cluster_id, host_meta):
            return {'host_meta': host_meta}

        self._enforce(req, 'add_host')
        if host_meta.has_key('resource_type'):
            if host_meta['resource_type'] not in self.support_resource_type:
                msg = "resource type is not supported, please use it in %s" % self.support_resource_type
                raise HTTPBadRequest(explanation=msg,
                                     request=req,
                                     content_type="text/plain")
        else:
            host_meta['resource_type'] = 'baremetal'

        if cluster_id:
            self.get_cluster_meta_or_404(req, cluster_id)
        if host_meta.has_key('role') and host_meta['role']:
            role_id_list = []
            host_roles=[]
            if host_meta.has_key('cluster'):
                params = self._get_query_params(req)
                role_list = registry.get_roles_detail(req.context, **params)
                for role_name in role_list:
                    if role_name['cluster_id'] == host_meta['cluster']:
                        host_roles = list(eval(host_meta['role']))
                        for host_role in host_roles:
                            if role_name['name'] == host_role:
                                role_id_list.append(role_name['id'])
                                continue
                if len(role_id_list) != len(host_roles):
                    msg = "The role of params %s is not exist, please use the right name" % host_roles
                    raise HTTPBadRequest(explanation=msg,
                                         request=req,
                                         content_type="text/plain")
                host_meta['role'] = role_id_list
            else:
                msg = "cluster params is none"
                raise HTTPBadRequest(explanation=msg,
                                     request=req,
                                     content_type="text/plain")

        assigned_networks = {}
        if host_meta.has_key('interfaces'):
            network_id_list = []
            orig_keys = list(eval(host_meta['interfaces']))
            for network in orig_keys:
                if network.has_key('is_deployment'):
                    if network['is_deployment'] == "True" or network['is_deployment'] == True:
                        network['is_deployment'] = 1
                    else:
                        network['is_deployment'] = 0
                if network.has_key('assigned_networks') and network['assigned_networks'] != [''] and network['assigned_networks']:
                    if host_meta.has_key('cluster'):
                        network_list = registry.get_networks_detail(req.context, host_meta['cluster'])
                        for network_name in list(network['assigned_networks']):
                            lenth = len(network_id_list)
                            for network_info in network_list:
                                if network_name == network_info['name']:
                                    network_id_list.append(network_info['id'])

                                    if network_info.get('id', None) \
                                        and network_info.get('name', None) \
                                        and network.get('name', None):
                                        assigned_networks[network_info['id']] = \
                                            [network_info.get('name', None), network.get('name', None)]
                            if lenth == len(network_id_list):
                                msg="The network of params %s is not exist, please use the right name" % network_name
                                raise HTTPBadRequest(explanation=msg,
                                                     request=req,
                                                     content_type="text/plain")
                        network['assigned_networks'] = network_id_list
                        # by cluster id and network_name search network table
                        registry.update_phyname_of_network(req.context, assigned_networks)
                    else:
                        msg = "cluster params is none"
                        raise HTTPBadRequest(explanation=msg,
                                             request=req,
                                             content_type="text/plain")
                if network.has_key('mac') and network.has_key('ip'):
                    host_infos = registry.get_host_interface(req.context, host_meta)
                    for host_info in host_infos:
                        if host_info.has_key('host_id'):
                            host_meta["id"] = host_info['host_id']

        if host_meta.has_key('os_status'):
            if host_meta['os_status'] not in ['init', 'installing', 'active', 'failed', 'none']:
                msg = "os_status is not valid."
                raise HTTPBadRequest(explanation=msg,
                                     request=req,
                                     content_type="text/plain")

        if host_meta.has_key('ipmi_addr') and host_meta['ipmi_addr']:
            if not host_meta.has_key('ipmi_user'):
                host_meta['ipmi_user'] = 'zteroot'
            if not host_meta.has_key('ipmi_passwd'):
                host_meta['ipmi_passwd'] = 'superuser'

        host_meta = registry.add_host_metadata(req.context, host_meta)

        return {'host_meta': host_meta}

    @utils.mutating
    def delete_host(self, req, id):
        """
        Deletes a host from Daisy.

        :param req: The WSGI/Webob Request object
        :param image_meta: Mapping of metadata about host

        :raises HTTPBadRequest if x-host-name is missing
        """
        self._enforce(req, 'delete_host')

        try:
            registry.delete_host_metadata(req.context, id)
        except exception.NotFound as e:
            msg = (_("Failed to find host to delete: %s") %
                   utils.exception_to_str(e))
            LOG.warn(msg)
            raise HTTPNotFound(explanation=msg,
                               request=req,
                               content_type="text/plain")
        except exception.Forbidden as e:
            msg = (_("Forbidden to delete host: %s") %
                   utils.exception_to_str(e))
            LOG.warn(msg)
            raise HTTPForbidden(explanation=msg,
                                request=req,
                                content_type="text/plain")
        except exception.InUseByStore as e:
            msg = (_("Host %(id)s could not be deleted because it is in use: "
                     "%(exc)s") % {"id": id, "exc": utils.exception_to_str(e)})
            LOG.warn(msg)
            raise HTTPConflict(explanation=msg,
                               request=req,
                               content_type="text/plain")
        else:
            #self.notifier.info('host.delete', host)
            return Response(body='', status=200)

    @utils.mutating
    def get_host(self, req, id):
        """
        Returns metadata about an host in the HTTP headers of the
        response object

        :param req: The WSGI/Webob Request object
        :param id: The opaque host identifier

        :raises HTTPNotFound if host metadata is not available to user
        """
        self._enforce(req, 'get_host')
        host_meta = self.get_host_meta_or_404(req, id)
        return {'host_meta': host_meta}

    def detail(self, req):
        """
        Returns detailed information for all available nodes

        :param req: The WSGI/Webob Request object
        :retval The response body is a mapping of the following form::

            {'nodes': [
                {'id': <ID>,
                 'name': <NAME>,
                 'description': <DESCRIPTION>,
                 'created_at': <TIMESTAMP>,
                 'updated_at': <TIMESTAMP>,
                 'deleted_at': <TIMESTAMP>|<NONE>,}, ...
            ]}
        """
        self._enforce(req, 'get_hosts')
        params = self._get_query_params(req)
        try:
            nodes = registry.get_hosts_detail(req.context, **params)
        except exception.Invalid as e:
            raise HTTPBadRequest(explanation=e.msg, request=req)
        return dict(nodes=nodes)

    def _verify_interface_in_same_host(self, interfaces, id = None):
        """
        Verify interface in the input host.
        :param interface: host interface info
        :return:
        """
        # verify interface among the input host
        interfaces = eval(interfaces)
        same_mac_list = [interface1['name']
                         for interface1 in interfaces for interface2 in interfaces
                         if interface1.get('name', None) and interface1.get('mac', None) and
                            interface2.get('name', None) and interface2.get('mac', None) and
                            interface1.get('type', None) and interface2.get('type', None) and
                         interface1['name'] != interface2['name'] and interface1['mac'] == interface2['mac']
                         and interface1['type'] != "bond" and interface2['type'] != "bond"]
        # Notice:If interface with same 'mac' is illegal,we need delete code #1,and raise exception in 'if' block.
        # This code block is just verify for early warning.
        if same_mac_list:
            msg = "%s%s" % ("" if not id else "Host id:%s." % id,
                            "The nic name of interface [%s] with same mac,please check!" %
                            ",".join(same_mac_list))
            LOG.warn(msg)

        # 1-----------------------------------------------------------------
        # if interface with same 'pci', raise exception
        same_pci_list = [interface1['name']
                         for interface1 in interfaces for interface2 in interfaces
                         if interface1.get('name', None) and interface1.get('pci', None) and
                             interface2.get('name', None) and interface2.get('pci', None) and
                            interface1.get('type', None) and interface2.get('type', None) and
                         interface1['name'] != interface2['name'] and interface1['pci'] == interface2['pci']
                         and interface1['type'] != "bond" and interface2['type'] != "bond"]

        if same_pci_list:
            msg = "The nic name of interface [%s] with same pci,please check!" % ",".join(same_pci_list)
            raise HTTPForbidden(explanation = msg)
        # 1-----------------------------------------------------------------

    def _verify_interface_among_hosts(self, req, cluster_id, host_meta):
        """
        Verify interface among the hosts in cluster
        :param req:
        :param cluster_id:
        :param host_meta:
        :return:
        """
        # If true, the host need update, not add and update is successful.
        host_is_update = False
        if not host_meta.get('interfaces', None):
            return host_is_update
        self._verify_interface_in_same_host(host_meta['interfaces'])

        # host pxe interface info
        interfaces = eval(host_meta['interfaces'])
        input_host_pxe_info = [interface
                               for interface in interfaces
                               if interface.get('is_deployment', None) == "True"]

        # In default,we think there is only one pxe interface.
        # If it not only the exception will be raise.
        if not input_host_pxe_info:
            LOG.info("<<<The host %s don't have pxe interface.>>>" % host_meta.get('name', None))
            return host_is_update

        if len(input_host_pxe_info) > 1:
            msg = ("There are two different pxe nics among the same host,it isn't allowed.")
            raise HTTPServerError(explanation = msg)

        if not cluster_id:
            return host_is_update

        # verify interface between exist host and input host in cluster
        list_params = {
            'sort_key': u'name',
            'sort_dir': u'asc',
            'limit': u'20',
            'filters': {u'cluster_id': cluster_id}
        }
        exist_nodes = registry.get_hosts_detail(req.context, **list_params)

        input_host_pxe_info = input_host_pxe_info[0]
        for exist_node in exist_nodes:
            id = exist_node.get('id', None)
            exist_node_info = self.get_host(req, id).get('host_meta', None)
            if not exist_node_info.get('interfaces', None):
                continue

            for interface in exist_node_info['interfaces']:
                if interface.get('mac', None) != input_host_pxe_info.get('mac', None):
                    continue
                if exist_node.get('dmi_uuid', None) != host_meta.get('dmi_uuid', None):
                    msg = "The 'mac' of host interface is exist in db, but 'dmi_uuid' is different." \
                          "We think you want update the host, but the host can't find."
                    raise HTTPForbidden(explanation = msg)

                host_meta['id'] = id
                host_meta['cluster_id'] = id
                self.update_host(req, id, host_meta)
                LOG.info("<<<FUN:verify_interface, host:%s is already update.>>>" % id)
                host_is_update = True
        return host_is_update
    def _get_swap_lv_size_m(self, memory_size_m):
        if memory_size_m <= 4096:
            swap_lv_size_m = 4096
        elif memory_size_m <= 16384:
            swap_lv_size_m = 8192
        elif memory_size_m <= 65536:
            swap_lv_size_m = 32768
        else:
            swap_lv_size_m = 65536
        return swap_lv_size_m

    @utils.mutating
    def update_host(self, req, id, host_meta):
        """
        Updates an existing host with the registry.

        :param request: The WSGI/Webob Request object
        :param id: The opaque image identifier

        :retval Returns the updated image information as a mapping
        """
        if host_meta.get('interfaces', None):
            self._verify_interface_in_same_host(host_meta['interfaces'], id)

        self._enforce(req, 'update_host')
        orig_host_meta = self.get_host_meta_or_404(req, id)
        # Do not allow any updates on a deleted image.
        # Fix for LP Bug #1060930
        if orig_host_meta['deleted']:
            msg = _("Forbidden to update deleted host.")
            raise HTTPForbidden(explanation=msg,
                                request=req,
                                content_type="text/plain")

        if host_meta.has_key('cluster'):
            self.get_cluster_meta_or_404(req, host_meta['cluster'])

        if (host_meta.has_key('resource_type') and
            host_meta['resource_type'] not in self.support_resource_type):
            msg = "resource type is not supported, please use it in %s" % self.support_resource_type
            raise HTTPNotFound(msg)

        if orig_host_meta.get('disks',None):
            if host_meta.get('os_status',None) != 'init' and orig_host_meta.get('os_status',None) == 'active':
                host_meta['root_disk'] = orig_host_meta['root_disk']
            else:
                if host_meta.get('root_disk',None):
                    root_disk = host_meta['root_disk']
                elif orig_host_meta.get('root_disk',None):
                    root_disk = str(orig_host_meta['root_disk'])
                else:
                    host_meta['root_disk'] = 'sda'
                    root_disk = host_meta['root_disk']
                if root_disk not in orig_host_meta['disks'].keys():
                    msg = "There is no disk named %s" % root_disk
                    raise HTTPBadRequest(explanation=msg,
                                        request=req,
                                        content_type="text/plain")
        else:
            host_meta['root_disk'] = orig_host_meta['root_disk']

        if orig_host_meta.get('disks',None):
            if host_meta.get('os_status',None) != 'init' and orig_host_meta.get('os_status',None) == 'active':
                host_meta['root_lv_size'] = orig_host_meta['root_lv_size']
            else:
                if host_meta.get('root_lv_size',None):
                    root_lv_size = host_meta['root_lv_size']
                elif orig_host_meta.get('root_lv_size',None):
                    root_lv_size = str(orig_host_meta['root_lv_size'])
                else:
                    host_meta['root_lv_size'] = '51200'
                    root_lv_size = host_meta['root_lv_size']

                if root_lv_size.isdigit():
                    root_lv_size=int(root_lv_size)
                    root_disk_storage_size_b_str = str(orig_host_meta['disks']['%s' %root_disk]['size'])
                    root_disk_storage_size_b_int = int(root_disk_storage_size_b_str.strip().split()[0])
                    root_disk_storage_size_m = root_disk_storage_size_b_int//(1024*1024)
                    boot_partition_m = 400
                    redundant_partiton_m = 100
                    free_root_disk_storage_size_m = root_disk_storage_size_m - boot_partition_m - redundant_partiton_m
                    if (root_lv_size/4)*4 > free_root_disk_storage_size_m:
                        msg = "root_lv_size of %s is larger than the free_root_disk_storage_size."%orig_host_meta['id']
                        raise HTTPForbidden(explanation=msg,
                                            request=req,
                                            content_type="text/plain")
                    if (root_lv_size/4)*4 < 51200:
                        msg = "root_lv_size of %s is too small ,it must be larger than 51200M."%orig_host_meta['id']
                        raise HTTPForbidden(explanation=msg,
                                            request=req,
                                            content_type="text/plain")
                else:
                    msg = (_("root_lv_size of %s is wrong,please input a number and it must be positive number") %orig_host_meta['id'])
                    raise HTTPForbidden(explanation=msg,
                                        request=req,
                                        content_type="text/plain")
        else:
            host_meta['root_lv_size'] = orig_host_meta['root_lv_size']

        if orig_host_meta.get('disks',None):
            if host_meta.get('os_status',None) != 'init' and orig_host_meta.get('os_status',None) == 'active':
                host_meta['swap_lv_size'] = orig_host_meta['swap_lv_size']
            else:
                if host_meta.get('swap_lv_size',None):
                    swap_lv_size = host_meta['swap_lv_size']
                elif orig_host_meta.get('swap_lv_size',None):
                    swap_lv_size = str(orig_host_meta['swap_lv_size'])
                else:
                    if not orig_host_meta.get('memory',None):
                        msg = "there is no memory in %s" %orig_host_meta['id']
                        raise HTTPNotFound(msg)
                    memory_size_b_str = str(orig_host_meta['memory']['total'])
                    memory_size_b_int = int(memory_size_b_str.strip().split()[0])
                    memory_size_m = memory_size_b_int//1024
                    swap_lv_size_m = self._get_swap_lv_size_m(memory_size_m)
                    host_meta['swap_lv_size'] = str(swap_lv_size_m)
                    swap_lv_size = host_meta['swap_lv_size']
                if swap_lv_size.isdigit():
                    swap_lv_size=int(swap_lv_size)
                    disk_storage_size_b = 0
                    for key in orig_host_meta['disks']:
                        stroage_size_str = orig_host_meta['disks'][key]['size']
                        stroage_size_b_int = int(stroage_size_str.strip().split()[0])
                        disk_storage_size_b = disk_storage_size_b + stroage_size_b_int
                    disk_storage_size_m = disk_storage_size_b/(1024*1024)
                    boot_partition_m = 400
                    redundant_partiton_m = 100
                    free_disk_storage_size_m = disk_storage_size_m - boot_partition_m - redundant_partiton_m - (root_lv_size/4)*4
                    if (swap_lv_size/4)*4 > free_disk_storage_size_m:
                        msg = "swap_lv_size of %s is larger than the free_disk_storage_size."%orig_host_meta['id']
                        raise HTTPForbidden(explanation=msg,
                                            request=req,
                                            content_type="text/plain")
                    if (swap_lv_size/4)*4 < 2000:
                        msg = "swap_lv_size of %s is too small ,it must be larger than 2000M."%orig_host_meta['id']
                        raise HTTPForbidden(explanation=msg,
                                            request=req,
                                            content_type="text/plain")
                else:
                    msg = (_("swap_lv_size of %s is wrong,please input a number and it must be positive number") %orig_host_meta['id'])
                    raise HTTPForbidden(explanation=msg,
                                        request=req,
                                        content_type="text/plain")
        else:
            host_meta['swap_lv_size'] = orig_host_meta['swap_lv_size']

        if orig_host_meta.get('disks',None):
            if not host_meta.get('root_pwd',None) and not orig_host_meta.get('root_pwd',None):
                host_meta['root_pwd'] = 'ossdbg1'
        else:
            host_meta['root_pwd'] = orig_host_meta['root_pwd']

        if host_meta.has_key('role'):
            role_id_list = []
            if host_meta.has_key('cluster'):
                params = self._get_query_params(req)
                role_list = registry.get_roles_detail(req.context, **params)
                host_roles = list()
                for role_name in role_list:
                    if role_name['cluster_id'] == host_meta['cluster']:
                        host_roles = list(eval(host_meta['role']))
                        for host_role in host_roles:
                            if role_name['name'] == host_role:
                                role_id_list.append(role_name['id'])
                                continue
                if len(role_id_list) != len(host_roles) and host_meta['role'] != u"[u'']":
                    msg = "The role of params %s is not exist, please use the right name" % host_roles
                    raise HTTPNotFound(msg)
                host_meta['role'] = role_id_list
            else:
                msg = "cluster params is none"
                raise HTTPNotFound(msg)

        assigned_networks = {}
        if host_meta.has_key('interfaces'):
            network_id_list = []
            orig_keys = list(eval(host_meta['interfaces']))
            for network in orig_keys:
                if network.has_key('is_deployment'):
                    if network['is_deployment'] == "True" or network['is_deployment'] == True:
                        network['is_deployment'] = 1
                    else:
                        network['is_deployment'] = 0
                if network.has_key('assigned_networks') and network['assigned_networks'] != [''] and network['assigned_networks']:
                    if host_meta.has_key('cluster'):
                        network_list = registry.get_networks_detail(req.context, host_meta['cluster'])
                        for network_name in list(network['assigned_networks']):
                            lenth = len(network_id_list)
                            for network_info in network_list:
                                if network_name == network_info['name']:
                                    network_id_list.append(network_info['id'])

                                    if network_info.get('id', None) \
                                        and network_info.get('name', None) \
                                        and network.get('name', None):
                                        assigned_networks[network_info['id']] = \
                                            [network_info.get('name', None), network.get('name', None)]
                            if lenth == len(network_id_list):
                                msg="The network of params %s is not exist, please use the right name" % network_name
                                raise HTTPNotFound(msg)

                        network['assigned_networks'] = network_id_list
                        # by cluster id and network_name search network table
                        registry.update_phyname_of_network(req.context, assigned_networks)
                    else:
                        msg = "cluster params is none"
                        raise HTTPNotFound(msg)

        if host_meta.has_key('os_status'):
            if host_meta['os_status'] not in ['init', 'installing', 'active', 'failed', 'none']:
                msg = "os_status is not valid."
                raise HTTPNotFound(msg)
            if host_meta['os_status'] == 'init':
                if orig_host_meta.get('interfaces', None):
                    macs = [interface['mac'] for interface in orig_host_meta['interfaces']]
                    for mac in macs:
                        delete_host_discovery_info = 'pxe_os_install_clean ' + mac
                        subprocess.call(delete_host_discovery_info,
                                        shell=True,
                                        stdout=open('/dev/null', 'w'),
                                        stderr=subprocess.STDOUT)
                if (not host_meta.has_key('role') and
                    orig_host_meta.has_key('status') and
                    orig_host_meta['status'] == 'with-role'):
                    host_meta['role'] = []

        if ((host_meta.has_key('ipmi_addr') and host_meta['ipmi_addr'])
            or orig_host_meta['ipmi_addr']):
            if not host_meta.has_key('ipmi_user') and not orig_host_meta['ipmi_user']:
                host_meta['ipmi_user'] = 'zteroot'
            if not host_meta.has_key('ipmi_passwd') and not orig_host_meta['ipmi_passwd']:
                host_meta['ipmi_passwd'] = 'superuser'

        try:
            host_meta = registry.update_host_metadata(req.context,
                                                      id,
                                                      host_meta)

        except exception.Invalid as e:
            msg = (_("Failed to update host metadata. Got error: %s") %
                   utils.exception_to_str(e))
            LOG.warn(msg)
            raise HTTPBadRequest(explanation=msg,
                                 request=req,
                                 content_type="text/plain")
        except exception.NotFound as e:
            msg = (_("Failed to find host to update: %s") %
                   utils.exception_to_str(e))
            LOG.warn(msg)
            raise HTTPNotFound(explanation=msg,
                               request=req,
                               content_type="text/plain")
        except exception.Forbidden as e:
            msg = (_("Forbidden to update host: %s") %
                   utils.exception_to_str(e))
            LOG.warn(msg)
            raise HTTPForbidden(explanation=msg,
                                request=req,
                                content_type="text/plain")
        except (exception.Conflict, exception.Duplicate) as e:
            LOG.warn(utils.exception_to_str(e))
            raise HTTPConflict(body=_('Host operation conflicts'),
                               request=req,
                               content_type='text/plain')
        else:
            self.notifier.info('host.update', host_meta)

        return {'host_meta': host_meta}

class HostDeserializer(wsgi.JSONRequestDeserializer):
    """Handles deserialization of specific controller method requests."""

    def _deserialize(self, request):
        result = {}
        result["host_meta"] = utils.get_host_meta(request)
        return result

    def add_host(self, request):
        return self._deserialize(request)

    def update_host(self, request):
        return self._deserialize(request)

class HostSerializer(wsgi.JSONResponseSerializer):
    """Handles serialization of specific controller method responses."""

    def __init__(self):
        self.notifier = notifier.Notifier()

    def add_host(self, response, result):
        host_meta = result['host_meta']
        response.status = 201
        response.headers['Content-Type'] = 'application/json'
        response.body = self.to_json(dict(host=host_meta))
        return response

    def delete_host(self, response, result):
        host_meta = result['host_meta']
        response.status = 201
        response.headers['Content-Type'] = 'application/json'
        response.body = self.to_json(dict(host=host_meta))
        return response

    def get_host(self, response, result):
        host_meta = result['host_meta']
        response.status = 201
        response.headers['Content-Type'] = 'application/json'
        response.body = self.to_json(dict(host=host_meta))
        return response

def create_resource():
    """Hosts resource factory method"""
    deserializer = HostDeserializer()
    serializer = HostSerializer()
    return wsgi.Resource(Controller(), deserializer, serializer)


text:
"""
Copyright (c) 2016-2017 Dell Inc. or its subsidiaries. All Rights Reserved.
"""

def test_one_of_two_pass():
    pass

def test_two_of_two_pass():
    pass


text:
using System;
using System.Collections.Generic;
using Microsoft.EntityFrameworkCore.Migrations;

namespace AnalyseVisitorsTool.Migrations
{
    public partial class Step5 : Migration
    {
        protected override void Up(MigrationBuilder migrationBuilder)
        {
            migrationBuilder.AddColumn<string>(
                name: "GoogleMapsAPIKey",
                table: "Setup",
                nullable: true);

            migrationBuilder.AddColumn<string>(
                name: "IPLocationAPIKey",
                table: "Setup",
                nullable: true);
        }

        protected override void Down(MigrationBuilder migrationBuilder)
        {
            migrationBuilder.DropColumn(
                name: "GoogleMapsAPIKey",
                table: "Setup");

            migrationBuilder.DropColumn(
                name: "IPLocationAPIKey",
                table: "Setup");
        }
    }
}


text:
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vhudson-jaxb-ri-2.1-2
// See http://java.sun.com/xml/jaxb
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2014.11.11 at 11:02:03 AM PST
//

package com.google.api.ads.adwords.lib.jaxb.v201402;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlType;

/**
 *
Java class for Paging complex type.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *
 *

 * <complexType name="Paging">
 *   <complexContent>
 *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *       <sequence>
 *         <element name="startIndex" type="{http://www.w3.org/2001/XMLSchema}int" minOccurs="0"/>
 *         <element name="numberResults" type="{http://www.w3.org/2001/XMLSchema}int" minOccurs="0"/>
 *       </sequence>
 *     </restriction>
 *   </complexContent>
 * </complexType>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "Paging", propOrder = {
    "startIndex",
    "numberResults"
})
public class Paging {

    protected Integer startIndex;
    protected Integer numberResults;

    /**
     * Gets the value of the startIndex property.
     *
     * @return
     *     possible object is
     *     {@link Integer }
     *
     */
    public Integer getStartIndex() {
        return startIndex;
    }

    /**
     * Sets the value of the startIndex property.
     *
     * @param value
     *     allowed object is
     *     {@link Integer }
     *
     */
    public void setStartIndex(Integer value) {
        this.startIndex = value;
    }

    /**
     * Gets the value of the numberResults property.
     *
     * @return
     *     possible object is
     *     {@link Integer }
     *
     */
    public Integer getNumberResults() {
        return numberResults;
    }

    /**
     * Sets the value of the numberResults property.
     *
     * @param value
     *     allowed object is
     *     {@link Integer }
     *
     */
    public void setNumberResults(Integer value) {
        this.numberResults = value;
    }

}