text:
//
//  HTTPTool.m
//  MyOne
//
//  Created by HelloWorld on 8/3/15.
//  Copyright (c) 2015 melody. All rights reserved.
//

#import "HTTPTool.h"

@implementation HTTPTool

+ (AFHTTPRequestOperationManager *)initAFHttpManager {
    static AFHTTPRequestOperationManager *manager;
    static dispatch_once_t once;
    dispatch_once(&once, ^{
        manager = [[AFHTTPRequestOperationManager alloc] init];
        manager.responseSerializer = [AFJSONResponseSerializer serializer];
        manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", @"text/html", @"text/plain", nil];
        manager.operationQueue.maxConcurrentOperationCount = 1;
    });

    return manager;
}

+ (NSDictionary *)parametersWithIndex:(NSInteger)index {
    if (index > 9) {
        NSString *date = [BaseFunction stringDateBeforeTodaySeveralDays:index];
        NSDictionary *parameters = @{ @"strDate" : date,
                                      @"strRow" : @"1" };

        return parameters;
    } else {
        NSString *date = [BaseFunction stringDateFromCurrent];
        NSDictionary *parameters = @{ @"strDate" : date,
                                      @"strRow" : [@(++index) stringValue] };

        return parameters;
    }
}

/**
 *  获取首页数据
 *
 *  @param date    日期,"yyyy-MM-dd"格式
 *  @param success 请求成功 Block
 *  @param fail     请求失败 Block
 */
+ (void)requestHomeContentByDate:(NSString *)date success:(SuccessBlock)success failBlock:(FailBlock)fail {
    AFHTTPRequestOperationManager *manager = [HTTPTool initAFHttpManager];
    NSDictionary *parameters = @{ @"strDate" : date,
                                  @"strRow" : [@1 stringValue] };
    [manager GET:URL_GET_HOME_CONTENT parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
        success(operation, responseObject);
    }
        failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            fail(operation, error);
        }];
}

/**
 *  获取首页数据
 *
 *  @param index   要展示数据的 Item 的下标
 *  @param success 请求成功 Block
 *  @param fail    请求失败 Block
 */
+ (void)requestHomeContentByIndex:(NSInteger)index success:(SuccessBlock)success failBlock:(FailBlock)fail {
    AFHTTPRequestOperationManager *manager = [HTTPTool initAFHttpManager];
    NSDictionary *parameters = [self parametersWithIndex:index];
    [manager GET:URL_GET_HOME_CONTENT parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
        success(operation, responseObject);
    }
        failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            fail(operation, error);
        }];
}

/**
 *  获取文章
 *
 *  @param date           日期,"yyyy-MM-dd"格式
 *  @param lastUpdateDate 最后更新日期,"yyyy-MM-dd"格式或者也可以是"yyyy-MM-dd HH:mm:ss"格式
 *  @param success        请求成功 Block
 *  @param fail           请求失败 Block
 */
+ (void)requestArticleContentByDate:(NSString *)date lastUpdateDate:(NSString *)lastUpdateDate success:(SuccessBlock)success failBlock:(FailBlock)fail {
    AFHTTPRequestOperationManager *manager = [HTTPTool initAFHttpManager];
    NSDictionary *parameters = @{ @"strDate" : date,
                                  @"strLastUpdateDate" : lastUpdateDate };
    [manager GET:URL_GET_READING_CONTENT parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
        success(operation, responseObject);
    }
        failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            fail(operation, error);
        }];
}

//+ (void)requestReadingContentByIndex:(NSInteger)index lastUpdateDate:(NSString *)lastUpdateDate success:(SuccessBlock)success failBlock:(FailBlock)fail {
//	AFHTTPRequestOperationManager *manager = [HTTPTool initAFHttpManager];
//	NSDictionary *parameters = @{@"strDate" : date, @"strLastUpdateDate" : lastUpdateDate};
//	[manager GET:URL_GET_READING_CONTENT parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
//		success(operation,responseObject);
//	} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
//		fail(operation,error);
//	}];
//}

/**
 *   获取问题
 *
 *  @param date           日期,"yyyy-MM-dd"格式
 *  @param lastUpdateDate 最后更新日期,"yyyy-MM-dd"格式
 *  @param success        请求成功 Block
 *  @param fail           请求失败 Block
 */
+ (void)requestQuestionContentByDate:(NSString *)date lastUpdateDate:(NSString *)lastUpdateDate success:(SuccessBlock)success failBlock:(FailBlock)fail {
    AFHTTPRequestOperationManager *manager = [HTTPTool initAFHttpManager];
    NSDictionary *parameters = @{ @"strDate" : date,
                                  @"strLastUpdateDate" : lastUpdateDate };
    [manager GET:URL_GET_QUESTION_CONTENT parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
        success(operation, responseObject);
    }
        failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            fail(operation, error);
        }];
}

//+ (void)requestQuestionContentByIndex:(NSInteger)index lastUpdateDate:(NSString *)lastUpdateDate success:(SuccessBlock)success failBlock:(FailBlock)fail {
//	AFHTTPRequestOperationManager *manager = [HTTPTool initAFHttpManager];
//	NSDictionary *parameters = @{@"strDate" : date, @"strLastUpdateDate" : lastUpdateDate};
//	[manager GET:URL_GET_QUESTION_CONTENT parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
//		success(operation,responseObject);
//	} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
//		fail(operation,error);
//	}];
//}

//+ (void)requestQuestionContentBackupByDate:(NSString *)date success:(SuccessBlock)success failBlock:(FailBlock)fail {
//	AFHTTPRequestOperationManager *manager = [HTTPTool initAFHttpManager];
//	NSDictionary *parameters = @{@"strDate" : date, @"strRow" : @"1"};
//	[manager GET:URL_BACKUP_GET_QUESTION_CONTENT parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
//		success(operation,responseObject);
//	} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
//		fail(operation,error);
//	}];
//}

/**
 *  获取东西
 *
 *  @param date    日期,"yyyy-MM-dd"格式
 *  @param success 请求成功 Block
 *  @param fail     请求失败 Block
 */
+ (void)requestThingContentByDate:(NSString *)date success:(SuccessBlock)success failBlock:(FailBlock)fail {
    AFHTTPRequestOperationManager *manager = [HTTPTool initAFHttpManager];
    NSDictionary *parameters = @{ @"strDate" : date,
                                  @"strRow" : @"1" };
    [manager GET:URL_GET_THING_CONTENT parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
        success(operation, responseObject);
    }
        failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            fail(operation, error);
        }];
}

/**
 *  获取东西
 *
 *  @param index   要展示数据的 Item 的下标
 *  @param success 请求成功 Block
 *  @param fail    请求失败 Block
 */
+ (void)requestThingContentByIndex:(NSInteger)index success:(SuccessBlock)success failBlock:(FailBlock)fail {
    AFHTTPRequestOperationManager *manager = [HTTPTool initAFHttpManager];
    NSDictionary *parameters = [self parametersWithIndex:index];
    [manager GET:URL_GET_THING_CONTENT parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
        success(operation, responseObject);
    }
        failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            fail(operation, error);
        }];
}

@end


text:
class FavoritesController < ApplicationController

  def create
    if current_user.nil?
      flash[:error] = "You must be logged in to save a favorite"
    else
      if v = Video.find_by_id( params[:video_id] ) and
         check_video_viz( v ) and
         ( current_user.favorites.all_videos << v ) and
         current_user.favorites.save and
         current_user.save
        flash[:notice] = "Added to Favorites"
      else
        flash[:error] = "Error adding favorite"
      end
    end
    redirect_to :back
  end

  def destroy
    if !current_user
      render_missing
      return
    end

    if params[:id].blank? or params[:id] == "0"
      render_missing
      return
    end

    if v = Video.find( params[:id] )
      current_user.favorites.all_videos.delete v
      flash[:notice] = "Deleted from Favorites"
    end

    redirect_to :back
  end

end

redpajama_set_name: RedPajamaGithub


text:
<?xml version='1.0' encoding='utf-8'?>
<widget id="br.ufscar.dc.latosensu.partiu" version="1.0.0" xmlns="http://www.w3.org/ns/widgets" xmlns:cdv="http://cordova.apache.org/ns/1.0">
    <feature name="LocalStorage">
        <param name="ios-package" value="CDVLocalStorage" />
    </feature>
    <feature name="HandleOpenUrl">
        <param name="ios-package" value="CDVHandleOpenURL" />
        <param name="onload" value="true" />
    </feature>
    <feature name="IntentAndNavigationFilter">
        <param name="ios-package" value="CDVIntentAndNavigationFilter" />
        <param name="onload" value="true" />
    </feature>
    <feature name="GestureHandler">
        <param name="ios-package" value="CDVGestureHandler" />
        <param name="onload" value="true" />
    </feature>
    <feature name="SplashScreen">
        <param name="ios-package" value="CDVSplashScreen" />
        <param name="onload" value="true" />
    </feature>
    <name>Partiu</name>
    <description>
        Este sistema apóia a gestão de viagens, hospedagens, deslocamentos, agendamentos e reservas em passeios, excursões, e outros eventos turísticos.
    </description>
    <author email="partiu@latosensu.dc.ufscar.br" href="http://latosensu.dc.ufscar.br/">
        Everton De Grande [evertondg@gmail.com],
        Eduardo Ponsoni [duponsoni@hotmail.com],
        Jacqueline Avansi [jacqueline_avansi@yahoo.com.br],
        Paul Kibe  [wacujuguna@gmail.com],
        Vitor Augusto Bellotto [bellotto.vitor@gmail.com],
        Wellington Camargo [mew.hkr@gmail.com]
  </author>
    <content src="index.html" />
    <access origin="*" />
    <allow-intent href="http://*/*" />
    <allow-intent href="https://*/*" />
    <allow-intent href="tel:*" />
    <allow-intent href="sms:*" />
    <allow-intent href="mailto:*" />
    <allow-intent href="geo:*" />
    <allow-navigation href="http://*/*" />
    <icon src="resources/android/icon/drawable-xhdpi-icon.png" />
    <allow-intent href="itms:*" />
    <allow-intent href="itms-apps:*" />
    <icon height="57" src="resources/ios/icon/icon.png" width="57" />
    <icon height="114" src="resources/ios/icon/icon@2x.png" width="114" />
    <icon height="40" src="resources/ios/icon/icon-40.png" width="40" />
    <icon height="80" src="resources/ios/icon/icon-40@2x.png" width="80" />
    <icon height="120" src="resources/ios/icon/icon-40@3x.png" width="120" />
    <icon height="50" src="resources/ios/icon/icon-50.png" width="50" />
    <icon height="100" src="resources/ios/icon/icon-50@2x.png" width="100" />
    <icon height="60" src="resources/ios/icon/icon-60.png" width="60" />
    <icon height="120" src="resources/ios/icon/icon-60@2x.png" width="120" />
    <icon height="180" src="resources/ios/icon/icon-60@3x.png" width="180" />
    <icon height="72" src="resources/ios/icon/icon-72.png" width="72" />
    <icon height="144" src="resources/ios/icon/icon-72@2x.png" width="144" />
    <icon height="76" src="resources/ios/icon/icon-76.png" width="76" />
    <icon height="152" src="resources/ios/icon/icon-76@2x.png" width="152" />
    <icon height="167" src="resources/ios/icon/icon-83.5@2x.png" width="167" />
    <icon height="29" src="resources/ios/icon/icon-small.png" width="29" />
    <icon height="58" src="resources/ios/icon/icon-small@2x.png" width="58" />
    <icon height="87" src="resources/ios/icon/icon-small@3x.png" width="87" />
    <splash height="1136" src="resources/ios/splash/Default-568h@2x~iphone.png" width="640" />
    <splash height="1334" src="resources/ios/splash/Default-667h.png" width="750" />
    <splash height="2208" src="resources/ios/splash/Default-736h.png" width="1242" />
    <splash height="2048" src="resources/ios/splash/Default-Portrait@2x~ipad.png" width="1536" />
    <splash height="1024" src="resources/ios/splash/Default-Portrait~ipad.png" width="768" />
    <splash height="960" src="resources/ios/splash/Default@2x~iphone.png" width="640" />
    <splash height="480" src="resources/ios/splash/Default~iphone.png" width="320" />
    <preference name="AllowInlineMediaPlayback" value="false" />
    <preference name="EnableViewportScale" value="false" />
    <preference name="KeyboardDisplayRequiresUserAction" value="true" />
    <preference name="MediaPlaybackRequiresUserAction" value="false" />
    <preference name="SuppressesIncrementalRendering" value="false" />
    <preference name="SuppressesLongPressGesture" value="false" />
    <preference name="Suppresses3DTouchGesture" value="false" />
    <preference name="GapBetweenPages" value="0" />
    <preference name="PageLength" value="0" />
    <preference name="PaginationBreakingMode" value="page" />
    <preference name="PaginationMode" value="unpaginated" />
    <preference name="webviewbounce" value="false" />
    <preference name="UIWebViewBounce" value="false" />
    <preference name="DisallowOverscroll" value="true" />
    <preference name="android-minSdkVersion" value="16" />
    <preference name="BackupWebStorage" value="none" />
    <preference name="SplashScreen" value="screen" />
    <preference name="orientation" value="portrait" />
    <preference name="SplashScreenDelay" value="10000" />
    <preference name="FadeSplashScreen" value="true" />
    <preference name="FadeSplashScreenDuration" value="750" />
    <preference name="ShowSplashScreenSpinner" value="false" />
    <preference name="xwalkVersion" value="18+" />
    <preference name="xwalkCommandLine" value="--disable-pull-to-refresh-effect" />
    <preference name="xwalkMode" value="embedded" />
    <preference name="xwalkMultipleApk" value="true" />
</widget>


text:
namespace Microsoft.Azure.Management.Monitor.Fluent.Models
{
    using Microsoft.Rest;
    using Microsoft.Rest.Serialization;
    using Newtonsoft.Json;
    using System.Collections;
    using System.Collections.Generic;
    using System.Linq;

    /// <summary>
    /// The alert rule object for patch operations.
    /// </summary>
    [Rest.Serialization.JsonTransformation]
    public partial class AlertRuleResourcePatchInner
    {
        /// <summary>
        /// Initializes a new instance of the AlertRuleResourcePatchInner
        /// class.
        /// </summary>
        public AlertRuleResourcePatchInner()
        {
            CustomInit();
        }

        /// <summary>
        /// Initializes a new instance of the AlertRuleResourcePatchInner
        /// class.
        /// </summary>
        /// <param name="name">the name of the alert rule.</param>
        /// <param name="isEnabled">the flag that indicates whether the alert
        /// rule is enabled.</param>
        /// <param name="condition">the condition that results in the alert
        /// rule being activated.</param>
        /// <param name="tags">Resource tags</param>
        /// <param name="description">the description of the alert rule that
        /// will be included in the alert email.</param>
        /// <param name="actions">the array of actions that are performed when
        /// the alert rule becomes active, and when an alert condition is
        /// resolved.</param>
        /// <param name="lastUpdatedTime">Last time the rule was updated in
        /// ISO8601 format.</param>
        public AlertRuleResourcePatchInner(string name, bool isEnabled, RuleCondition condition, IDictionary<string, string> tags = default(IDictionary<string, string>), string description = default(string), IList<RuleAction> actions = default(IList<RuleAction>), System.DateTime? lastUpdatedTime = default(System.DateTime?))
        {
            Tags = tags;
            Name = name;
            Description = description;
            IsEnabled = isEnabled;
            Condition = condition;
            Actions = actions;
            LastUpdatedTime = lastUpdatedTime;
            CustomInit();
        }

        /// <summary>
        /// An initialization method that performs custom operations like setting defaults
        /// </summary>
        partial void CustomInit();

        /// <summary>
        /// Gets or sets resource tags
        /// </summary>
        [JsonProperty(PropertyName = "tags")]
        public IDictionary<string, string> Tags { get; set; }

        /// <summary>
        /// Gets or sets the name of the alert rule.
        /// </summary>
        [JsonProperty(PropertyName = "properties.name")]
        public string Name { get; set; }

        /// <summary>
        /// Gets or sets the description of the alert rule that will be
        /// included in the alert email.
        /// </summary>
        [JsonProperty(PropertyName = "properties.description")]
        public string Description { get; set; }

        /// <summary>
        /// Gets or sets the flag that indicates whether the alert rule is
        /// enabled.
        /// </summary>
        [JsonProperty(PropertyName = "properties.isEnabled")]
        public bool IsEnabled { get; set; }

        /// <summary>
        /// Gets or sets the condition that results in the alert rule being
        /// activated.
        /// </summary>
        [JsonProperty(PropertyName = "properties.condition")]
        public RuleCondition Condition { get; set; }

        /// <summary>
        /// Gets or sets the array of actions that are performed when the alert
        /// rule becomes active, and when an alert condition is resolved.
        /// </summary>
        [JsonProperty(PropertyName = "properties.actions")]
        public IList<RuleAction> Actions { get; set; }

        /// <summary>
        /// Gets last time the rule was updated in ISO8601 format.
        /// </summary>
        [JsonProperty(PropertyName = "properties.lastUpdatedTime")]
        public System.DateTime? LastUpdatedTime { get; private set; }

        /// <summary>
        /// Validate the object.
        /// </summary>
        /// <exception cref="ValidationException">
        /// Thrown if validation fails
        /// </exception>
        public virtual void Validate()
        {
            if (Name == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "Name");
            }
            if (Condition == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "Condition");
            }
        }
    }
}


text:
package org.cinchapi.concourse.server.storage.db;

import java.util.Map;
import java.util.Set;

import org.cinchapi.concourse.server.io.Byteable;

import com.google.common.collect.Maps;

/**
 * A {@link Record} that can return a browsable view of its data in the present
 * or a historical state.
 *
 * @author Jeff Nelson
 */
abstract class BrowsableRecord<L extends Byteable & Comparable<L>, K extends Byteable & Comparable<K>, V extends Byteable & Comparable<V>>
        extends Record<L, K, V> {

    /**
     * Construct a new instance.
     *
     * @param locator
     * @param key
     */
    protected BrowsableRecord(L locator, K key) {
        super(locator, key);
    }

    /**
     * Return a view of all the data that is presently contained in this record.
     *
     * @return the data
     */
    public Map<K, Set<V>> browse() {
        read.lock();
        try {
            Map<K, Set<V>> data = Maps.newLinkedHashMap();
            for (K key : describe()) {
                data.put(key, get(key));
            }
            return data;
        }
        finally {
            read.unlock();
        }

    }

    /**
     * Return a view of all the data that was contained in this record at
     * {@code timestamp}.
     *
     * @param timestamp
     * @return the data
     */
    public Map<K, Set<V>> browse(long timestamp) {
        read.lock();
        try {
            Map<K, Set<V>> data = Maps.newLinkedHashMap();
            for (K key : describe(timestamp)) {
                data.put(key, get(key, timestamp));
            }
            return data;
        }
        finally {
            read.unlock();
        }
    }

}


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

namespace _18_19.GroupStudents
{
    class GroupStudents
    {
        /// <summary>
        /// 18.Create a program that extracts all students grouped by GroupName and then prints them to the console. Use LINQ.
        /// </summary>
        static void GroupByGroupNameWithLinq()
        {
            var studentsGroupedByGroupNameWithLinq =
                from student in students
                group student by student.GroupName into newGroup
                orderby newGroup.Key
                select newGroup;

            foreach (var currentGroup in studentsGroupedByGroupNameWithLinq)
            {
                Console.ForegroundColor = ConsoleColor.Cyan;
                Console.WriteLine(currentGroup.Key);
                Console.ResetColor();

                foreach (var student in currentGroup)
                {
                    Console.WriteLine(student.FullName);
                }
                Console.WriteLine();
            }
        }

        /// <summary>
        /// 19.Rewrite the previous using extension methods.
        /// </summary>
        static void GroupByGroupNameWithLambda()
        {
            var studentsGroupedByGroupNameWithLambda = students.GroupBy(x => x.GroupName).OrderBy(x => x.Key);

            foreach (var currentGroup in studentsGroupedByGroupNameWithLambda)
            {
                Console.ForegroundColor = ConsoleColor.Magenta;
                Console.WriteLine(currentGroup.Key);
                Console.ResetColor();

                foreach (var student in currentGroup)
                {
                    Console.WriteLine(student.FullName);
                }
                Console.WriteLine();
            }
        }

        static Student[] students;
        static void Main()
        {
            students = new Student[]
            {
                new Student("Petar Marinov", "Goal"),
                new Student("Mariq Dimova", "Millenium"),
                new Student("Anna Gargorova", "Millenium"),
                new Student("Maraq Kaleva", "Greaters"),
                new Student("Georgi Dobrev", "Millenium"),
                new Student("Valentin Shopov", "Greaters")
            };

            GroupByGroupNameWithLinq();

            GroupByGroupNameWithLambda();
        }
    }
}


text:
define(['performer/core'], function(_) {

  var Constructor = function() {

    this.register = function(name, method) {
      this[name] = method;
    };

  };

  var Helpers = new Constructor();

  Helpers.register('attr_html', function(schema, ignore_value) {
    var attributes = _.map(schema, function(val,key) {
      if(_.isEmpty(val) || (ignore_value && key == 'value')) {
        return null;
      }
      if(key === 'className') { key = 'class'; }
      return key+"=\""+_.escape(val)+"\"";
    });

    return _.compact(attributes).join(' ');
  });

  Helpers.register('titleize', function(name) {
    if(!name) { return ""; }

    name = name.toLowerCase()
               .replace('_', ' ')
               .split(' ');

    return name.map(function(word) {
      return word.substring(0, 1).toUpperCase() + word.substring(1);
    }).join(' ');

  });

  return Helpers;
});


text:
form_is_submitted
=================


text:
const _ = require('lodash');

module.exports = {
  find: async function (params, populate, raw = false) {
    const query = this
      .find(params.where)
      .limit(Number(params.limit))
      .sort(params.sort)
      .skip(Number(params.skip))
      .populate(populate || this.associations.map(x => x.alias).join(' '));

    return raw ? query.lean() : query;
  },

  count: async function (params) {
    return Number(await this
      .where(params.where)
      .count());
  },

  search: async function (params, populate) { // eslint-disable-line  no-unused-vars
    const $or = Object.keys(this.attributes).reduce((acc, curr) => {
      switch (this.attributes[curr].type) {
        case 'integer':
        case 'float':
        case 'decimal':
          if (!_.isNaN(_.toNumber(params.search))) {
            return acc.concat({ [curr]: params.search });
          }

          return acc;
        case 'string':
        case 'text':
        case 'password':
          return acc.concat({ [curr]: { $regex: params.search, $options: 'i' } });
        case 'boolean':
          if (params.search === 'true' || params.search === 'false') {
            return acc.concat({ [curr]: params.search === 'true' });
          }

          return acc;
        default:
          return acc;
      }
    }, []);

    return this
      .find({ $or })
      .limit(Number(params.limit))
      .sort(params.sort)
      .skip(Number(params.skip))
      .populate(populate || this.associations.map(x => x.alias).join(' '))
      .lean();
  },

  countSearch: async function (params = {}) { // eslint-disable-line  no-unused-vars
    const $or = Object.keys(this.attributes).reduce((acc, curr) => {
      switch (this.attributes[curr].type) {
        case 'integer':
        case 'float':
        case 'decimal':
          if (!_.isNaN(_.toNumber(params.search))) {
            return acc.concat({ [curr]: params.search });
          }

          return acc;
        case 'string':
        case 'text':
        case 'password':
          return acc.concat({ [curr]: { $regex: params.search, $options: 'i' } });
        case 'boolean':
          if (params.search === 'true' || params.search === 'false') {
            return acc.concat({ [curr]: params.search === 'true' });
          }

          return acc;
        default:
          return acc;
      }
    }, []);

    return this
      .find({ $or })
      .count();
  },

  findOne: async function (params, populate, raw = true) {
    const query = this
      .findOne({
        [this.primaryKey]: params[this.primaryKey] || params.id
      })
      .populate(populate || this.associations.map(x => x.alias).join(' '));

    return raw ? query.lean() : query;
  },

  create: async function (params) {
    // Exclude relationships.
    const values = Object.keys(params.values).reduce((acc, current) => {
      if (this._attributes[current] && this._attributes[current].type) {
        acc[current] = params.values[current];
      }

      return acc;
    }, {});

    const request = await this.create(values)
      .catch((err) => {
        if (err.message) {
          const message = err.message.split('index:');
          const field = _.words(_.last(message).split('_')[0]);
          err = { message: `This ${field} is already taken`, field };
        }
        throw err;
      });

    // Transform to JSON object.
    const entry = request.toJSON ? request.toJSON() : request;

    // Extract relations.
    const relations = this.associations.reduce((acc, association) => {
      if (params.values[association.alias]) {
        acc[association.alias] = params.values[association.alias];
      }

      return acc;
    }, {});

    return module.exports.update.call(this, {
      [this.primaryKey]: entry[this.primaryKey],
      values: _.assign({
        id: entry[this.primaryKey]
      }, relations)
    });
  },

  update: async function (params) {
    // Call the business logic located in the hook.
    // This function updates no-relational and relational data.
    return this.updateRelations(params);
  },

  delete: async function (params) {
    // Delete entry.
    return this
      .remove({
        [this.primaryKey]: params.id
      });
  },

  deleteMany: async function (params) {
    return this
      .remove({
        [this.primaryKey]: {
          $in: params[this.primaryKey] || params.id
        }
      });
  }
};


text:
-- --------------------------------------------------------
-- Host:                         raspi3.local.binggl.net
-- Server Version:               10.0.29-MariaDB-0+deb8u1 - (Raspbian)
-- Server Betriebssystem:        debian-linux-gnueabihf
-- HeidiSQL Version:             9.4.0.5168
-- --------------------------------------------------------

/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET NAMES utf8 */;
/*!50503 SET NAMES utf8mb4 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;

-- Exportiere Struktur von Tabelle login.login
DROP TABLE IF EXISTS `login`;
CREATE TABLE IF NOT EXISTS `login` (
  `Id` int(11) NOT NULL AUTO_INCREMENT,
  `Created` datetime(6) NOT NULL,
  `Modified` datetime(6) NOT NULL,
  `Type` int(11) NOT NULL,
  `UserDisplayName` varchar(128) COLLATE utf8_unicode_ci NOT NULL,
  `UserName` varchar(128) COLLATE utf8_unicode_ci NOT NULL,
  PRIMARY KEY (`Id`)
) ENGINE=InnoDB AUTO_INCREMENT=19 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

-- Daten Export vom Benutzer nicht ausgewählt
-- Exportiere Struktur von Tabelle login.user
DROP TABLE IF EXISTS `user`;
CREATE TABLE IF NOT EXISTS `user` (
  `Email` varchar(128) COLLATE utf8_unicode_ci NOT NULL,
  `Created` datetime(6) NOT NULL,
  `DisplayName` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  `Modified` datetime(6) NOT NULL,
  `Name` varchar(128) COLLATE utf8_unicode_ci NOT NULL,
  `Timestamp` longblob,
  PRIMARY KEY (`Email`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

-- Daten Export vom Benutzer nicht ausgewählt
-- Exportiere Struktur von Tabelle login.usersite
DROP TABLE IF EXISTS `usersite`;
CREATE TABLE IF NOT EXISTS `usersite` (
  `Name` varchar(128) COLLATE utf8_unicode_ci NOT NULL,
  `Created` datetime(6) NOT NULL,
  `Modified` datetime(6) NOT NULL,
  `PermissionList` longtext COLLATE utf8_unicode_ci NOT NULL,
  `Timestamp` longblob,
  `Url` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  `UserEmail` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
  PRIMARY KEY (`Name`),
  KEY `IX_usersite_UserEmail` (`UserEmail`),
  CONSTRAINT `FK_usersite_user_UserEmail` FOREIGN KEY (`UserEmail`) REFERENCES `user` (`Email`) ON DELETE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

-- Daten Export vom Benutzer nicht ausgewählt
/*!40101 SET SQL_MODE=IFNULL(@OLD_SQL_MODE, '') */;
/*!40014 SET FOREIGN_KEY_CHECKS=IF(@OLD_FOREIGN_KEY_CHECKS IS NULL, 1, @OLD_FOREIGN_KEY_CHECKS) */;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;


text:
<?php

/**
 * Profile_photo
 *
 * This class has been auto-generated by the Doctrine ORM Framework
 *
 * @package    sf_sandbox
 * @subpackage model
 * @author     Your name here
 * @version    SVN: $Id: Builder.php 7490 2010-03-29 19:53:27Z jwage $
 */
class Profile_photo extends PluginProfile_photo
{
}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="author" content="">

    <title>David Piatt - Student at The Ohio State University</title>

    <link href="css/bootstrap.min.css" rel="stylesheet">

    <link href="css/landing-page.css" rel="stylesheet">

    <link href="font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css">
    <link href="http://fonts.googleapis.com/css?family=Lato:300,400,700,300italic,400italic,700italic" rel="stylesheet" type="text/css">

                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
                    Toggle navigation

                </button>
                Home

                        About

                        Education

                        Projects

                        Expierence

                        Contact

David Piatt

Student at The Ohio State University

                                 Twitter

                                 Github

                                 Linkedin

                                OSU Student Blog

Contact Information:

Full Name:
 David Alexander Piatt

Email:
 piatt.50@osu.edu

Phone Number:

 740-357-0775

 Current Address:

 141 W 11th. Ave.

Columbus Ohio 43210

 Permanent Address:

 634 Randolph Ct.

 Worthington Ohio 43085

Education:

I finished high school at Thomas Worthington High School in Worthington Ohio with a 3.9 GPA. I'm currently a second year student at The Ohio State University studying computer science and engineering with a minor in Humanitarian Engineering. Currently I'm focused on learning penetration testing and big data analysis. I'm involve with the Big Data and Analytics Association and the Swim club.

Work Expierence

One Year of work at Access 2 Interpreters

September 2014 – September 2015 Columbus Ohio

Certified medical Spanish Interpreter.

Communicated through translation and Interpretation.

Taking emergencies on call

Taking scheduled appointments across Columbus

Summer Internship in Badu Analytical Chemistry Lab

May 2014 – August 2014 Columbus Ohio

Preparing samples to analyze under Mass Spectrometer

Working in experiment design with the Primary Investigator

Setting up lab with Principal Investigator

Summer Internship in Schoenberg Biomedical Lab

May 2013 – August 2013 Columbus Ohio
Position: Lab assistant

Direct involvement with the Primary Investigator and other lab assistants in formulating and executing experiments

Work with labeling and storing project samples

Work with independently extracting and analyzing DNA

Projects

These are my most recent accomplishments, I'm always trying to grow my skill set. Check back regularly to see my newest endevor.

Twitter Scraper

Fall Semester 2015

To Learn more please see my OSU blog

Directly Communicates with the Twitter API

Stores information surrounding a hashtag in multiple array lists

Graphs selected information against number of tweets in the database

Learned to use Python for real world coding

Utilized several Python libraries like MatPlotLib for data graphing, Tkinter for building the GUI, and Tweepy for API access.

 See more here!

Personal Resume

Winter Break 2015

Coded using a bootstrap kit

Used knowledge of HTML to properly finish coding the website

Linked to personal blogs and included open source pictures and content

Learned to use the unix terminal for ssh and remote hosting access

Learned about open source licensing and how to efficiently build web pages

Advanced Energy Vehicle Project

Fall Semester 2015, Introduction to Engineering 2

Coded vehicle using Arduino interface

Learned to work in a team for the development of a semester long project

Learned to properly document a project being worked on by many people

Learned to manage time and make meeting time efficient

Learned to properly utilize online meeting spaces for collaborating

 See more!

Password: humanitarianengineering

 What's Next?

                        I'd like to develop an Android app that in some way solves a simple problem that someone has. If you would like me to attempt this for you please contact me and I will get on it. Apart from that a friend and I are going to try and develop the Twitter scraper more to make it more useful and give the user more powerful data analysis abilities. In my free time I will be reading about penetration testing and doing examples, however I feel that I will need an internship in a security firm to fully grasp the technology. I'm interested in any Internship or free lance work!

Connect with David Piatt:

                             Twitter

                             Github

                             Linkedin

                                OSU Student Blog

                            Home

                        About

                        Education

                        Projects

                        Expierence

                        Contact

Copyright © Apache 2.0 Bootstrap edition. All Rights Reserved


text:
<?php

defined('JPATH_PLATFORM') or die;

JFormHelper::loadFieldClass('list');

/**
 * Module Tag field.
 *
 * @since  3.0
 */
class JFormFieldModuletag extends JFormFieldList
{
	/**
	 * The form field type.
	 *
	 * @var    string
	 * @since  3.0
	 */
	protected $type = 'ModuleTag';

	/**
	 * Method to get the field options.
	 *
	 * @return  array  The field option objects.
	 *
	 * @since   3.0
	 */
	protected function getOptions()
	{
		$options = array();
		$tags    = array('address', 'article', 'aside', 'details', 'div', 'footer', 'header', 'main', 'nav', 'section', 'summary');

		// Create one new option object for each tag
		foreach ($tags as $tag)
		{
			$tmp = JHtml::_('select.option', $tag, $tag);
			$options[] = $tmp;
		}

		reset($options);

		return $options;
	}
}


text:
class Fragment < ApplicationRecord
  # Avoid N+1s: Fragment.includes(Fragment::EVERYTHING)
  EVERYTHING = { nodes: Node::EVERYTHING }
  belongs_to :device
  belongs_to :owner, polymorphic: true, inverse_of: :fragment
  has_many :primitives, dependent: :destroy
  has_many :nodes
  has_many :primitive_pairs
  has_many :standard_pairs
  has_many :arg_sets
  before_destroy :clean_nodes

  def clean_nodes
    Node.where(fragment_id: self.id).destroy_all
  end

  def serialize(*x)
    Rails
      .cache
      .fetch(json_cache_key) { Fragments::Show.run!(owner: self.owner) }
  end

  def json_cache_key
    ["fragments", id, updated_at.to_i].join(":")
  end

  def self.from_celery(device:, kind:, args:, body:, owner:)
    p = { device: device, kind: kind, args: args, body: body }
    flat_ast = Fragments::Preprocessor.run!(**p)
    Fragments::Create.run!(device: device,
                           flat_ast: flat_ast,
                           owner: owner)
  end

  def broadcast?
    false
  end

  def self.remove_old_fragments_for_device(dev)
    dev.fragments.select { |x| x.owner == nil }.map { |x| x.destroy! }
  end
end


text:
#import "ANTitleValueCell.h"

@implementation ANTitleValueCell

@end


text:
from __future__ import absolute_import

import os
import shutil
import sys
import unittest
import solvebio
import solvebio.cli.credentials as creds
import contextlib

@contextlib.contextmanager
def nostdout():
    savestderr = sys.stdout

    class Devnull(object):
        def write(self, _):
            pass
    sys.stdout = Devnull()
    try:
        yield
    finally:
        sys.stdout = savestderr

class TestCredentials(unittest.TestCase):
    def setUp(self):
        self.solvebiodir = os.path.join(os.path.dirname(__file__),
                                        'data', '.solvebio')
        self.api_host = solvebio.api_host
        solvebio.api_host = 'https://api.solvebio.com'

    def tearDown(self):
        solvebio.api_host = self.api_host
        if os.path.isdir(self.solvebiodir):
            shutil.rmtree(self.solvebiodir)

    def test_credentials(self):

        datadir = os.path.join(os.path.dirname(__file__), 'data')
        os.environ['HOME'] = datadir

        # Make sure we don't have have the test solvebio directory
        if os.path.isdir(self.solvebiodir):
            shutil.rmtree(self.solvebiodir)

        cred_file = creds.netrc.path()
        self.assertTrue(os.path.exists(cred_file),
                        "cred file created when it doesn't exist first")

        self.assertEqual(creds.get_credentials(), None,
                         'Should not find credentials')

        test_credentials_file = os.path.join(datadir, 'test_creds')
        shutil.copy(test_credentials_file, cred_file)

        auths = creds.get_credentials()
        self.assertTrue(auths is not None, 'Should find credentials')

        solvebio.api_host = 'https://example.com'

        auths = creds.get_credentials()
        self.assertEqual(auths, None,
                         'Should not find credentials for host {0}'
                         .format(solvebio.api_host))

        solvebio.api_host = 'https://api.solvebio.com'
        creds.delete_credentials()
        auths = creds.get_credentials()
        self.assertEqual(auths, None,
                         'Should not find removed credentials for '
                         'host {0}'.format(solvebio.api_host))

        pair = ('testagain@solvebio.com', 'b00b00',)
        creds.save_credentials(*pair)
        auths = creds.get_credentials()
        self.assertTrue(auths is not None,
                        'Should get newly set credentials for '
                        'host {0}'.format(solvebio.api_host))

        expected = (solvebio.api_host, pair[0], 'Token', pair[1])
        self.assertEqual(auths, expected, 'Should get back creds we saved')


text:
<?xml version="1.0" encoding="utf-8"?>
<!--
   Copyright 2015 Synced Synapse. All rights reserved.

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
-->
<resources>
    <dimen name="wizard_title">216dp</dimen>

    <dimen name="remote_icon_size">126dp</dimen>

    <dimen name="remote_poster_width">96dp</dimen>
    <dimen name="remote_poster_height">162dp</dimen>

    <dimen name="now_playing_poster_width">140dp</dimen>
    <dimen name="now_playing_poster_height">200dp</dimen>
    <dimen name="now_playing_poster_margin_top">140dp</dimen>
    <dimen name="now_playing_art_height">324dp</dimen>

    <dimen name="media_title_margin_top">324dp</dimen>
    <dimen name="poster_width_plus_padding">180dp</dimen>

    <dimen name="default_grid_column_width">250dp</dimen>

    <dimen name="playlist_art_width">68dp</dimen>
    <dimen name="playlist_art_heigth">86dp</dimen>

    <dimen name="movielist_art_width">86dp</dimen>
    <dimen name="movielist_art_heigth">124dp</dimen>

    <dimen name="tvshowlist_art_width">86dp</dimen>
    <dimen name="tvshowlist_art_heigth">124dp</dimen>

    <dimen name="seasonlist_art_width">86dp</dimen>
    <dimen name="seasonlist_art_heigth">124dp</dimen>

    <dimen name="episodelist_art_width">134dp</dimen>
    <dimen name="episodelist_art_heigth">76dp</dimen>

    <dimen name="artistlist_art_width">88dp</dimen>
    <dimen name="artistlist_art_heigth">88dp</dimen>

    <dimen name="albumlist_art_width">88dp</dimen>
    <dimen name="albumlist_art_heigth">88dp</dimen>

    <dimen name="albumdetail_poster_width">136dp</dimen>
    <dimen name="albumdetail_poster_heigth">136dp</dimen>

    <dimen name="audiogenrelist_art_width">88dp</dimen>
    <dimen name="audiogenrelist_art_heigth">88dp</dimen>

    <dimen name="musicvideolist_art_width">88dp</dimen>
    <dimen name="musicvideolist_art_heigth">88dp</dimen>

    <dimen name="musicvideodetail_poster_width">146dp</dimen>
    <dimen name="musicvideodetail_poster_heigth">146dp</dimen>

    <dimen name="addonlist_art_width">88dp</dimen>
    <dimen name="addonlist_art_heigth">88dp</dimen>

    <dimen name="addondetail_poster_width">146dp</dimen>
    <dimen name="addondetail_poster_heigth">146dp</dimen>

    <dimen name="channellist_art_width">88dp</dimen>
    <dimen name="channellist_art_heigth">88dp</dimen>

    <dimen name="recordinglist_art_width">88dp</dimen>
    <dimen name="recordinglist_art_heigth">88dp</dimen>

</resources>


text:
// <copyright file="Program.cs" company="LipGam">
//      Copyright © LipGam Gaming Community. All rights reserved.
// </copyright>

namespace LipGam.SE.Scripting.PressurizationMonitoring
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using LipGam.SE.Scripting.Common;
    using Sandbox.ModAPI.Ingame;
    using Sandbox.ModAPI.Interfaces;
    using VRageMath;

    /// <summary>
    /// Script class for door display controlling.
    /// </summary>
    internal class Program
    {
        /// <summary>
        /// The station in which the script runs.
        /// </summary>
        private Station station;

        /// <summary>
        /// Initializes a new instance of the <see cref="Program" /> class.
        /// </summary>
        /// <param name="gridProgram">The grid Program.</param>
        public Program(MyGridProgram gridProgram)
        {
            GridProgram = gridProgram;
        }

        /// <summary>
        /// Gets the game program.
        /// </summary>
        private MyGridProgram GridProgram { get; }

        /// <summary>
        /// Entry point of the script.
        /// </summary>
        /// <param name="argument">The script argument provided by executing block.</param>
        public void Main(string argument)
        {
            StringBuilder debugStringBuilder = new StringBuilder();
            IMyTextPanel debugPanel = GridProgram.GridTerminalSystem.GetBlockWithName("DebugLCD") as IMyTextPanel;
            debugPanel?.GetProperty("FontColor").AsColor().SetValue(debugPanel, Color.White);
            if (station == null)
            {
                station = new Station();
                station.RequiresAspect<RoomPressure>();
                station.RequiresAspect<LockRoomOnPressureDecrease>();
                station.InitializeFromGrid(GridProgram.GridTerminalSystem);
            }

            try
            {
                int roomNameWidth = station.Rooms.Max(r => r.Name?.Length ?? 0);
                int severity = 0;
                StringBuilder stringBuilder = new StringBuilder();
                foreach (IGrouping<string, IRoom> grouping in station.Rooms.GroupBy(r => r.Section).OrderBy(g => g.Key))
                {
                    stringBuilder.AppendLine("SEKTION " + grouping.Key);
                    foreach (IRoom room in grouping.OrderBy(r => r.Section))
                    {
                        RoomPressure pressure = room.GetAspect<RoomPressure>();
                        pressure.UpdateAspect();
                        if (pressure.Status == RoomPressure.PressureStatus.Unknown)
                        {
                            debugStringBuilder.AppendLine($"Room without pressure data: Section {room.Section} {room.Name}");
                            continue;
                        }

                        if ((pressure.Status == RoomPressure.PressureStatus.Decreasing) || (pressure.Pressure < 0.2))
                        {
                            severity = 2;
                        }
                        else if ((pressure.Status == RoomPressure.PressureStatus.Decreasing) || (pressure.Pressure < 0.8))
                        {
                            severity = Math.Max(severity, 1);
                        }

                        LockRoomOnPressureDecrease locking = room.GetAspect<LockRoomOnPressureDecrease>();
                        locking.UpdateAspect();

                        string roomText = (room.Name ?? string.Empty).PadRight(roomNameWidth);
                        string pressureText = (pressure.Pressure * 100).ToString("F0").PadLeft(3);
                        string statusText = pressure.Status.ToString().PadRight(10);
                        string lockedText = locking.Locked ? "! Locked !" : string.Empty;
                        stringBuilder.AppendLine($"    {roomText}  {pressureText}% {statusText}   {lockedText}");
                    }
                    stringBuilder.AppendLine();
                }

                Color foreground;
                switch (severity)
                {
                    case 0:
                        foreground = Color.Green;
                        break;
                    case 1:
                        foreground = Color.Yellow;
                        break;
                    default:
                        foreground = Color.Red;
                        break;
                }

                IMyTextPanel textPanel = GridProgram.GridTerminalSystem.GetBlockWithName("PressureLCD") as IMyTextPanel;
                textPanel.WritePublicText(stringBuilder);
                textPanel.ShowPublicTextOnScreen();
                textPanel.GetProperty("FontColor").AsColor().SetValue(textPanel, foreground);
            }
            catch (Exception e)
            {
                debugPanel?.GetProperty("FontColor").AsColor().SetValue(debugPanel, Color.DarkRed);
                debugStringBuilder.AppendLine(e.ToString());
            }

            debugPanel?.WritePublicText(debugStringBuilder);
            debugPanel?.ShowPublicTextOnScreen();
        }

        /// <summary>
        /// Saves the persistent state of the script.
        /// </summary>
        public void Save()
        {
            // the script does not have a state to persist.
        }
    }
}


text:
![CI](https://github.com/ArtLabBocconi/BeliefPropagation.jl/workflows/CI/badge.svg)
[![codecov](https://codecov.io/gh/ArtLabBocconi/BeliefPropagation.jl/branch/master/graph/badge.svg?token=EWNYPD7ASX)](https://codecov.io/gh/ArtLabBocconi/BeliefPropagation.jl)

Implementation of Belief Propagation (BP) message passing for:

- Ising model (`Ising` module)
- Minimum weight perfect matching (`Matching` module)
- Minimum weight perfect b-matching (`BMatching` module)

Package is still experimental and not thoroughly tested, use it at your own risk.
Code contributions are very welcome!

## Installation

```julia
]add https://github.com/ArtLabBocconi/BeliefPropagation.jl
```

## Usage

Problem instances can be created using [Erdos](https://github.com/CarloLucibello/Erdos.jl) graph library. Problems are passed to  BP methods as Network objects with features attached to edges and vertices.

### Ising

```julia
using BeliefPropagation.Ising
using Erdos

# Create Ising model on ErdosRenyi graph
# with random couplings and constant external field.
net = erdos_renyi(100, 0.02, Network)
eprop!(net, "J", e -> randn())
vprop!(net, "H", v -> 1)

## Run Belief Propagation at some temperature
### and extract magnetizations
fg = Ising.run_bp(net, T=2, maxiters=100);
fg.mags
```

### Matching

```julia
using BeliefPropagation.Matching
using Erdos
using LinearAlgebra

# Create an instance of the random assignment problem
net = CompleteBipartiteGraph(100, 100, Network)
pos = [rand(2) for i in 1:nv(net)]
eprop!(net, "w", e -> norm(pos[src(e)] .- pos[dst(e)]))

## Run Belief Propagation and obtain optimal cost and matching
E, match = Matching.run_bp(net, maxiters=100);
```

The algorithm is guaranteed to return exact solutions only on bipartite graphs
(altough it may also work on non-bipartite).

### B-Matching

Solve an instance of the minimum-weight perfect b-matching problem.

```julia
using BeliefPropagation.BMatching
using Erdos
using LinearAlgebra

# Create an instance of the random assignment problem
net = CompleteGraph(100, Network)
eprop!(net, "w", e -> rand())
vprop!(net, "b", v -> rand(1:5))

## Run Belief Propagation and obtain optimal cost and matching
E, match = BMatching.run_bp(net, maxiters=100);
```

## Related Packages

- [SAT.jl](https://github.com/CarloLucibello/SAT.jl): a BP solver for SAT problems.
- [ForneyLab.jl](https://github.com/biaslab/ForneyLab.jl): Bayesian inference algorithms through message passing on Forney-style factor graphs.
- [BinaryCommitteeMachineFBP.jl](BinaryCommitteeMachineFBP.jl): Focusing Belief Propagation on commitee machines (neural network with one-hidden layer and a single output) with binary weights.

## TODO

Problems to be implemented:

- Low Density Parity Check codes (LDPC)
- coloring
- xorsat
- Potts models
- Steiner tree

Computation of Bethe free energies is also missing.


text:
<?php

$lang['modulerequire'] = "PHP Module Require";


text:
package se.vidstige.jadb.test.unit;

import org.junit.Assert;
import org.junit.Test;
import se.vidstige.jadb.AdbFilterInputStream;
import se.vidstige.jadb.Stream;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

public class AdbInputStreamFixture {

    private byte[] passthrough(byte[] input) throws IOException {
        ByteArrayInputStream inputStream = new ByteArrayInputStream(input);
        InputStream sut = new AdbFilterInputStream(inputStream);
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        Stream.copy(sut, output);
        return output.toByteArray();
    }

    @Test
    public void testSimple() throws Exception {
        byte[] actual = passthrough(new byte[]{ 1, 2, 3});
        Assert.assertArrayEquals(new byte[]{ 1, 2, 3}, actual);
    }

    @Test
    public void testEmpty() throws Exception {
        byte[] actual = passthrough(new byte[]{});
        Assert.assertArrayEquals(new byte[]{}, actual);
    }

    @Test
    public void testSimpleRemoval() throws Exception {
        byte[] actual = passthrough(new byte[]{0x0d, 0x0a});
        Assert.assertArrayEquals(new byte[]{0x0a}, actual);
    }

    @Test
    public void testDoubleRemoval() throws Exception {
        byte[] actual = passthrough(new byte[]{0x0d, 0x0a, 0x0d, 0x0a});
        Assert.assertArrayEquals(new byte[]{0x0a, 0x0a}, actual);
    }
}


text:
package com.skysport.interfaces.action.info.base;

import com.skysport.core.action.BaseAction;
import com.skysport.core.annotation.SystemControllerLog;
import com.skysport.core.bean.page.DataTablesInfo;
import com.skysport.core.bean.system.SelectItem2;
import com.skysport.core.model.seqno.service.IncrementNumberService;
import com.skysport.interfaces.constant.WebConstants;
import com.skysport.interfaces.bean.info.SeriesInfo;
import com.skysport.core.model.common.ICommonService;
import com.skysport.interfaces.model.info.series.SeriesManageServiceHelper;
import com.skysport.interfaces.utils.BuildSeqNoHelper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;

/**
 * 类描述的是:系列
 * Created by zhangjh on 2015/6/9.
 */
@Scope("prototype")
@Controller
@RequestMapping("/system/series")
public class SeriesAction extends BaseAction<SeriesInfo> {
    @Resource(name = "seriesManageService")
    private ICommonService seriesManageService;

    @Resource(name = "incrementNumber")
    private IncrementNumberService incrementNumberService;

    /**
     * 此方法描述的是:展示list页面	 *
     *
     * @author: zhangjh
     * @version: 2015年4月29日 下午5:34:53
     */
    @RequestMapping(value = "/list")
    @ResponseBody
    @SystemControllerLog(description = "点击系列菜单")
    public ModelAndView search() {
        ModelAndView mav = new ModelAndView("/system/series/list");
        return mav;
    }

    /**
     * 此方法描述的是:
     *
     * @author: zhangjh
     * @version: 2015年4月29日 下午5:34:53
     */
    @RequestMapping(value = "/search")
    @ResponseBody
    @SystemControllerLog(description = "查询系列信息列表")
    public Map<String, Object> search(HttpServletRequest request) {
        // HashMap<String, String> paramMap = convertToMap(params);
        DataTablesInfo dataTablesInfo = convertToDataTableQrInfo(WebConstants.SERIES_TABLE_COLUMN, request);
        // 总记录数
        int recordsTotal = seriesManageService.listInfosCounts();
        int recordsFiltered = recordsTotal;
        if (!StringUtils.isBlank(dataTablesInfo.getSearchValue())) {
            recordsFiltered = seriesManageService.listFilteredInfosCounts(dataTablesInfo);
        }
        int draw = Integer.parseInt(request.getParameter("draw"));
        List<SeriesInfo> seriesInfos = seriesManageService.searchInfos(dataTablesInfo);
        Map<String, Object> resultMap = buildSearchJsonMap(seriesInfos, recordsTotal, recordsFiltered, draw);

        return resultMap;
    }

    /**
     * 此方法描述的是:
     *
     * @author: zhangjh
     * @version: 2015年4月29日 下午5:35:09
     */
    @RequestMapping(value = "/edit", method = RequestMethod.POST)
    @ResponseBody
    @SystemControllerLog(description = "编辑系列")
    public Map<String, Object> edit(SeriesInfo seriesInfo, HttpServletRequest request,
                                    HttpServletResponse respones) {
        seriesManageService.edit(seriesInfo);

        SeriesManageServiceHelper.SINGLETONE.refreshSelect();
        return rtnSuccessResultMap("更新成功");
    }

    /**
     * 此方法描述的是:
     *
     * @author: zhangjh
     * @version: 2015年4月29日 下午5:35:09
     */
    @RequestMapping(value = "/new", method = RequestMethod.POST)
    @ResponseBody
    @SystemControllerLog(description = "新增系列")
    public Map<String, Object> add(SeriesInfo seriesInfo, HttpServletRequest request) {
        String currentNo = seriesManageService.queryCurrentSeqNo();
        //设置ID
        seriesInfo.setNatrualkey(BuildSeqNoHelper.SINGLETONE.getNextSeqNo(WebConstants.SERIES_INFO, currentNo, incrementNumberService));
        seriesManageService.add(seriesInfo);

        SeriesManageServiceHelper.SINGLETONE.refreshSelect();
        return rtnSuccessResultMap("新增成功");
    }

    /**
     * @param natrualKey   主键id
     * @param request      请求信息
     * @param reseriesonse 返回信息
     * @return 根据主键id找出详细信息
     */
    @RequestMapping(value = "/info/{natrualKey}", method = RequestMethod.GET)
    @ResponseBody
    @SystemControllerLog(description = "查询系列信息")
    public SeriesInfo info(@PathVariable String natrualKey, HttpServletRequest request, HttpServletResponse reseriesonse) {
        SeriesInfo seriesInfo = (SeriesInfo) seriesManageService.queryInfoByNatrualKey(natrualKey);
        return seriesInfo;
    }

    /**
     * @param natrualKey
     * @return
     */
    @RequestMapping(value = "/del/{natrualKey}", method = RequestMethod.DELETE)
    @ResponseBody
    @SystemControllerLog(description = "删除系列")
    public Map<String, Object> del(@PathVariable String natrualKey) {
        seriesManageService.del(natrualKey);
        SeriesManageServiceHelper.SINGLETONE.refreshSelect();
        return rtnSuccessResultMap("删除成功");
    }

    @RequestMapping(value = "/select", method = RequestMethod.GET)
    @ResponseBody
    public Map<String, Object> querySelectList(HttpServletRequest request) {
        String name = request.getParameter("name");
        List<SelectItem2> commonBeans = seriesManageService.querySelectList(name);
        return rtSelectResultMap(commonBeans);
    }

}


text:
package armsql_test

import (
	"context"
	"log"

	"github.com/Azure/azure-sdk-for-go/sdk/azcore/to"
	"github.com/Azure/azure-sdk-for-go/sdk/azidentity"
	"github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/sql/armsql"
)

// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/tree/main/specification/sql/resource-manager/Microsoft.Sql/preview/2021-05-01-preview/examples/ManagedInstanceListByInstancePool.json
func ExampleManagedInstancesClient_NewListByInstancePoolPager() {
	cred, err := azidentity.NewDefaultAzureCredential(nil)
	if err != nil {
		log.Fatalf("failed to obtain a credential: %v", err)
	}
	ctx := context.Background()
	client, err := armsql.NewManagedInstancesClient("20D7082A-0FC7-4468-82BD-542694D5042B", cred, nil)
	if err != nil {
		log.Fatalf("failed to create client: %v", err)
	}
	pager := client.NewListByInstancePoolPager("Test1",
		"pool1",
		&armsql.ManagedInstancesClientListByInstancePoolOptions{Expand: nil})
	for pager.More() {
		nextResult, err := pager.NextPage(ctx)
		if err != nil {
			log.Fatalf("failed to advance page: %v", err)
		}
		for _, v := range nextResult.Value {
			// TODO: use page item
			_ = v
		}
	}
}

// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/tree/main/specification/sql/resource-manager/Microsoft.Sql/preview/2021-05-01-preview/examples/ManagedInstanceList.json
func ExampleManagedInstancesClient_NewListPager() {
	cred, err := azidentity.NewDefaultAzureCredential(nil)
	if err != nil {
		log.Fatalf("failed to obtain a credential: %v", err)
	}
	ctx := context.Background()
	client, err := armsql.NewManagedInstancesClient("20D7082A-0FC7-4468-82BD-542694D5042B", cred, nil)
	if err != nil {
		log.Fatalf("failed to create client: %v", err)
	}
	pager := client.NewListPager(&armsql.ManagedInstancesClientListOptions{Expand: nil})
	for pager.More() {
		nextResult, err := pager.NextPage(ctx)
		if err != nil {
			log.Fatalf("failed to advance page: %v", err)
		}
		for _, v := range nextResult.Value {
			// TODO: use page item
			_ = v
		}
	}
}

// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/tree/main/specification/sql/resource-manager/Microsoft.Sql/preview/2021-05-01-preview/examples/ManagedInstanceListByResourceGroup.json
func ExampleManagedInstancesClient_NewListByResourceGroupPager() {
	cred, err := azidentity.NewDefaultAzureCredential(nil)
	if err != nil {
		log.Fatalf("failed to obtain a credential: %v", err)
	}
	ctx := context.Background()
	client, err := armsql.NewManagedInstancesClient("20D7082A-0FC7-4468-82BD-542694D5042B", cred, nil)
	if err != nil {
		log.Fatalf("failed to create client: %v", err)
	}
	pager := client.NewListByResourceGroupPager("Test1",
		&armsql.ManagedInstancesClientListByResourceGroupOptions{Expand: nil})
	for pager.More() {
		nextResult, err := pager.NextPage(ctx)
		if err != nil {
			log.Fatalf("failed to advance page: %v", err)
		}
		for _, v := range nextResult.Value {
			// TODO: use page item
			_ = v
		}
	}
}

// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/tree/main/specification/sql/resource-manager/Microsoft.Sql/preview/2021-05-01-preview/examples/ManagedInstanceGet.json
func ExampleManagedInstancesClient_Get() {
	cred, err := azidentity.NewDefaultAzureCredential(nil)
	if err != nil {
		log.Fatalf("failed to obtain a credential: %v", err)
	}
	ctx := context.Background()
	client, err := armsql.NewManagedInstancesClient("20d7082a-0fc7-4468-82bd-542694d5042b", cred, nil)
	if err != nil {
		log.Fatalf("failed to create client: %v", err)
	}
	res, err := client.Get(ctx,
		"testrg",
		"testinstance",
		&armsql.ManagedInstancesClientGetOptions{Expand: nil})
	if err != nil {
		log.Fatalf("failed to finish the request: %v", err)
	}
	// TODO: use response item
	_ = res
}

// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/tree/main/specification/sql/resource-manager/Microsoft.Sql/preview/2021-05-01-preview/examples/ManagedInstanceCreateMax.json
func ExampleManagedInstancesClient_BeginCreateOrUpdate() {
	cred, err := azidentity.NewDefaultAzureCredential(nil)
	if err != nil {
		log.Fatalf("failed to obtain a credential: %v", err)
	}
	ctx := context.Background()
	client, err := armsql.NewManagedInstancesClient("20D7082A-0FC7-4468-82BD-542694D5042B", cred, nil)
	if err != nil {
		log.Fatalf("failed to create client: %v", err)
	}
	poller, err := client.BeginCreateOrUpdate(ctx,
		"testrg",
		"testinstance",
		armsql.ManagedInstance{
			Location: to.Ptr("Japan East"),
			Tags: map[string]*string{
				"tagKey1": to.Ptr("TagValue1"),
			},
			Properties: &armsql.ManagedInstanceProperties{
				AdministratorLogin:         to.Ptr("dummylogin"),
				AdministratorLoginPassword: to.Ptr("PLACEHOLDER"),
				Administrators: &armsql.ManagedInstanceExternalAdministrator{
					AzureADOnlyAuthentication: to.Ptr(true),
					Login:                     to.Ptr("bob@contoso.com"),
					PrincipalType:             to.Ptr(armsql.PrincipalTypeUser),
					Sid:                       to.Ptr("00000011-1111-2222-2222-123456789111"),
					TenantID:                  to.Ptr("00000011-1111-2222-2222-123456789111"),
				},
				Collation:                        to.Ptr("SQL_Latin1_General_CP1_CI_AS"),
				DNSZonePartner:                   to.Ptr("/subscriptions/20D7082A-0FC7-4468-82BD-542694D5042B/resourceGroups/testrg/providers/Microsoft.Sql/managedInstances/testinstance"),
				InstancePoolID:                   to.Ptr("/subscriptions/20D7082A-0FC7-4468-82BD-542694D5042B/resourceGroups/testrg/providers/Microsoft.Sql/instancePools/pool1"),
				LicenseType:                      to.Ptr(armsql.ManagedInstanceLicenseTypeLicenseIncluded),
				MaintenanceConfigurationID:       to.Ptr("/subscriptions/20D7082A-0FC7-4468-82BD-542694D5042B/providers/Microsoft.Maintenance/publicMaintenanceConfigurations/SQL_JapanEast_MI_1"),
				MinimalTLSVersion:                to.Ptr("1.2"),
				ProxyOverride:                    to.Ptr(armsql.ManagedInstanceProxyOverrideRedirect),
				PublicDataEndpointEnabled:        to.Ptr(false),
				RequestedBackupStorageRedundancy: to.Ptr(armsql.BackupStorageRedundancyGeo),
				ServicePrincipal: &armsql.ServicePrincipal{
					Type: to.Ptr(armsql.ServicePrincipalTypeSystemAssigned),
				},
				StorageSizeInGB: to.Ptr[int32](1024),
				SubnetID:        to.Ptr("/subscriptions/20D7082A-0FC7-4468-82BD-542694D5042B/resourceGroups/testrg/providers/Microsoft.Network/virtualNetworks/vnet1/subnets/subnet1"),
				TimezoneID:      to.Ptr("UTC"),
				VCores:          to.Ptr[int32](8),
			},
			SKU: &armsql.SKU{
				Name: to.Ptr("GP_Gen5"),
				Tier: to.Ptr("GeneralPurpose"),
			},
		},
		nil)
	if err != nil {
		log.Fatalf("failed to finish the request: %v", err)
	}
	res, err := poller.PollUntilDone(ctx, nil)
	if err != nil {
		log.Fatalf("failed to pull the result: %v", err)
	}
	// TODO: use response item
	_ = res
}

// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/tree/main/specification/sql/resource-manager/Microsoft.Sql/preview/2021-05-01-preview/examples/ManagedInstanceDelete.json
func ExampleManagedInstancesClient_BeginDelete() {
	cred, err := azidentity.NewDefaultAzureCredential(nil)
	if err != nil {
		log.Fatalf("failed to obtain a credential: %v", err)
	}
	ctx := context.Background()
	client, err := armsql.NewManagedInstancesClient("20D7082A-0FC7-4468-82BD-542694D5042B", cred, nil)
	if err != nil {
		log.Fatalf("failed to create client: %v", err)
	}
	poller, err := client.BeginDelete(ctx,
		"testrg",
		"testinstance",
		nil)
	if err != nil {
		log.Fatalf("failed to finish the request: %v", err)
	}
	_, err = poller.PollUntilDone(ctx, nil)
	if err != nil {
		log.Fatalf("failed to pull the result: %v", err)
	}
}

// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/tree/main/specification/sql/resource-manager/Microsoft.Sql/preview/2021-05-01-preview/examples/ManagedInstanceRemoveMaintenanceConfiguration.json
func ExampleManagedInstancesClient_BeginUpdate() {
	cred, err := azidentity.NewDefaultAzureCredential(nil)
	if err != nil {
		log.Fatalf("failed to obtain a credential: %v", err)
	}
	ctx := context.Background()
	client, err := armsql.NewManagedInstancesClient("20D7082A-0FC7-4468-82BD-542694D5042B", cred, nil)
	if err != nil {
		log.Fatalf("failed to create client: %v", err)
	}
	poller, err := client.BeginUpdate(ctx,
		"testrg",
		"testinstance",
		armsql.ManagedInstanceUpdate{
			Properties: &armsql.ManagedInstanceProperties{
				MaintenanceConfigurationID: to.Ptr("/subscriptions/20d7082a-0fc7-4468-82bd-542694d5042b/providers/Microsoft.Maintenance/publicMaintenanceConfigurations/SQL_Default"),
			},
		},
		nil)
	if err != nil {
		log.Fatalf("failed to finish the request: %v", err)
	}
	res, err := poller.PollUntilDone(ctx, nil)
	if err != nil {
		log.Fatalf("failed to pull the result: %v", err)
	}
	// TODO: use response item
	_ = res
}

// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/tree/main/specification/sql/resource-manager/Microsoft.Sql/preview/2021-05-01-preview/examples/ManagedInstanceTopQueriesList.json
func ExampleManagedInstancesClient_NewListByManagedInstancePager() {
	cred, err := azidentity.NewDefaultAzureCredential(nil)
	if err != nil {
		log.Fatalf("failed to obtain a credential: %v", err)
	}
	ctx := context.Background()
	client, err := armsql.NewManagedInstancesClient("00000000-1111-2222-3333-444444444444", cred, nil)
	if err != nil {
		log.Fatalf("failed to create client: %v", err)
	}
	pager := client.NewListByManagedInstancePager("sqlcrudtest-7398",
		"sqlcrudtest-4645",
		&armsql.ManagedInstancesClientListByManagedInstanceOptions{NumberOfQueries: nil,
			Databases:           nil,
			StartTime:           nil,
			EndTime:             nil,
			Interval:            to.Ptr(armsql.QueryTimeGrainTypePT1H),
			AggregationFunction: nil,
			ObservationMetric:   to.Ptr(armsql.MetricTypeDuration),
		})
	for pager.More() {
		nextResult, err := pager.NextPage(ctx)
		if err != nil {
			log.Fatalf("failed to advance page: %v", err)
		}
		for _, v := range nextResult.Value {
			// TODO: use page item
			_ = v
		}
	}
}

// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/tree/main/specification/sql/resource-manager/Microsoft.Sql/preview/2021-05-01-preview/examples/FailoverManagedInstance.json
func ExampleManagedInstancesClient_BeginFailover() {
	cred, err := azidentity.NewDefaultAzureCredential(nil)
	if err != nil {
		log.Fatalf("failed to obtain a credential: %v", err)
	}
	ctx := context.Background()
	client, err := armsql.NewManagedInstancesClient("00000000-1111-2222-3333-444444444444", cred, nil)
	if err != nil {
		log.Fatalf("failed to create client: %v", err)
	}
	poller, err := client.BeginFailover(ctx,
		"group1",
		"instanceName",
		&armsql.ManagedInstancesClientBeginFailoverOptions{ReplicaType: to.Ptr(armsql.ReplicaTypePrimary)})
	if err != nil {
		log.Fatalf("failed to finish the request: %v", err)
	}
	_, err = poller.PollUntilDone(ctx, nil)
	if err != nil {
		log.Fatalf("failed to pull the result: %v", err)
	}
}