text:
<file_sep>module Types.Pos exposing (Pos, mapRow, mapCol)

type alias Pos =
    { row : Int, col : Int }

mapRow : (Int -> Int) -> Pos -> Pos
mapRow fn pos =
    { pos | row = fn pos.row }

mapCol : (Int -> Int) -> Pos -> Pos
mapCol fn pos =
    { pos | col = fn pos.col }
<file_sep>module Subscriptions exposing (subscriptions)

import Model exposing (Model)
import Messages exposing (Msg(..))
import Types.Common exposing (Direction(..))
import Types.GameState exposing (GameState(..))
import Keyboard
import Time

subscriptions : Model -> Sub Msg
subscriptions model =
    case model.state of
        NotStarted ->
            Keyboard.downs startGameOnSpace

        Paused _ ->
            Sub.batch
                [ Keyboard.downs resumeOnR
                , Keyboard.downs newGameOnN
                ]

        Running _ ->
            Sub.batch
                [ Time.every
                    (Time.millisecond * toFloat (500 - (10 * model.speed)))
                    (always Tick)
                , Keyboard.downs moveBrick
                , Keyboard.downs rotateBrick
                , Keyboard.downs dropPieceOnEnter
                , Keyboard.downs pauseOnP
                ]

        GameOver _ ->
            Keyboard.downs startGameOnSpace

pauseOnP : Keyboard.KeyCode -> Msg
pauseOnP keyCode =
    if keyCode == 80 then
        PauseGame
    else
        NoOp

resumeOnR : Keyboard.KeyCode -> Msg
resumeOnR keyCode =
    if keyCode == 82 then
        ResumeGame
    else
        NoOp

dropPieceOnEnter : Keyboard.KeyCode -> Msg
dropPieceOnEnter keyCode =
    if keyCode == 13 then
        Drop
    else
        NoOp

startGameOnSpace : Keyboard.KeyCode -> Msg
startGameOnSpace keyCode =
    if keyCode == 32 then
        StartNewGame
    else
        NoOp

newGameOnN : Keyboard.KeyCode -> Msg
newGameOnN keyCode =
    if keyCode == 78 then
        StartNewGame
    else
        NoOp

moveBrick : Keyboard.KeyCode -> Msg
moveBrick keyCode =
    case keyCode of
        37 ->
            Move Left

        39 ->
            Move Right

        40 ->
            Move Down

        _ ->
            NoOp

rotateBrick : Keyboard.KeyCode -> Msg
rotateBrick keyCode =
    case keyCode of
        38 ->
            Rotate

        _ ->
            NoOp
<file_sep>module Types.Board
    exposing
        ( Board
        , Cell(..)
        , empty
        , clearFullRows
        , getCell
        , toPosList
        , addPiece
        , legalOn
        , moveToBottom
        )

import Array exposing (Array)
import Types.Pos exposing (Pos)
import Types.Common exposing (Color(..), Direction(..))
import Types.Piece as Piece exposing (Piece)
import Config

type alias Board =
    Array (Array Cell)

type Cell
    = Empty
    | Filled Color

empty : Board
empty =
    Array.repeat Config.height <| Array.repeat Config.width Empty

clearFullRows : Board -> ( Board, Int )
clearFullRows board =
    let
        filteredRows =
            Array.filter (Array.toList >> List.any ((==) Empty)) board

        rowsRemoved =
            Array.length board - Array.length filteredRows

        replacementRows =
            Array.repeat rowsRemoved (Array.repeat Config.width Empty)
    in
        ( Array.append replacementRows filteredRows
        , rowsRemoved
        )

getCell : Pos -> Board -> Maybe Cell
getCell pos board =
    board
        |> Array.get pos.row
        |> Maybe.map (Array.get pos.col)
        |> Maybe.withDefault Nothing

setCell : Pos -> Cell -> Board -> Board
setCell pos cell board =
    let
        maybeRow =
            board
                |> Array.get pos.row
                |> Maybe.map (Array.set pos.col cell)
    in
        case maybeRow of
            Just row ->
                Array.set pos.row row board

            Nothing ->
                board

toPosList : Board -> List ( Pos, Cell )
toPosList board =
    Array.map (Array.toIndexedList) board
        |> Array.toIndexedList
        |> List.concatMap
            (\( row, cells ) ->
                cells
                    |> List.map
                        (\( col, cell ) ->
                            ( Pos row col, cell )
                        )
            )

addPiece : Piece -> Board -> Board
addPiece piece board =
    List.foldl
        (\pos -> setCell pos <| Filled piece.color)
        board
        (Piece.positions piece)

legalOn : Board -> Piece -> Bool
legalOn board piece =
    let
        insideLeftEdge =
            List.all (\pos -> pos.col >= 0) (Piece.positions piece)

        insideRightEdge =
            List.all (\pos -> pos.col < Config.width) (Piece.positions piece)

        aboveBottom =
            List.all (\pos -> pos.row <= Config.height) (Piece.positions piece)

        collision =
            List.any (\pos -> (getCell pos board) /= Just Empty) (Piece.positions piece)
    in
        insideLeftEdge && insideRightEdge && aboveBottom && not collision

moveToBottom : Board -> Piece -> Piece
moveToBottom board piece =
    if not <| legalOn board (Piece.move Down piece) then
        piece
    else
        moveToBottom board (Piece.move Down piece)
<file_sep>module Messages exposing (Msg(..))

import Types.Common exposing (Direction)
import Types.Piece exposing (Piece)

type Msg
    = NoOp
    | StartNewGame
    | NewGame Piece Piece
    | NewPiece Piece
    | Tick
    | Move Direction
    | Rotate
    | Drop
    | PauseGame
    | ResumeGame
<file_sep>module Update exposing (update)

import Config
import Types.Common exposing (..)
import Types.Board as Board exposing (Board, Cell(..))
import Types.Piece as Piece exposing (Piece)
import Types.GameState as GameState exposing (GameState(..))
import Messages exposing (Msg(..))
import Model exposing (Model)
import Random

update : Msg -> Model -> ( Model, Cmd Msg )
update msg model =
    case msg of
        NoOp ->
            ( model, Cmd.none )

        NewGame currentPiece nextPiece ->
            ( { model
                | state = Running 0
                , speed = 1
                , board = Board.empty
                , currentPiece = currentPiece
                , nextPiece = nextPiece
              }
            , Cmd.none
            )

        PauseGame ->
            ( { model
                | state = Paused <| GameState.score model.state
              }
            , Cmd.none
            )

        ResumeGame ->
            ( { model
                | state = Running <| GameState.score model.state
              }
            , Cmd.none
            )

        Drop ->
            ( { model
                | currentPiece = Board.moveToBottom model.board model.currentPiece
              }
            , Cmd.none
            )

        StartNewGame ->
            ( model
            , Random.generate identity <|
                Random.map2 NewGame
                    Piece.random
                    Piece.random
            )

        NewPiece piece ->
            ( if piece |> Board.legalOn model.board then
                { model
                    | currentPiece = model.nextPiece
                    , nextPiece = piece
                }
              else
                { model
                    | state = GameOver <| GameState.score model.state
                }
            , Cmd.none
            )

        Tick ->
            let
                movedPiece =
                    Piece.move Down model.currentPiece
            in
                if movedPiece |> Board.legalOn model.board then
                    ( { model | currentPiece = movedPiece }
                    , Cmd.none
                    )
                else
                    let
                        ( newBoard, numClearedRows ) =
                            model.board
                                |> Board.addPiece model.currentPiece
                                |> Board.clearFullRows

                        newSpeed =
                            if numClearedRows > 0 then
                                model.speed + 1
                            else
                                model.speed
                    in
                        ( { model
                            | board = newBoard
                            , currentPiece = Piece.empty
                            , state = model.state |> GameState.addPoints (numClearedRows * numClearedRows)
                            , speed = newSpeed
                          }
                        , Random.generate NewPiece Piece.random
                        )

        Move direction ->
            ( { model
                | currentPiece = moveIfPossible direction model.board model.currentPiece
              }
            , Cmd.none
            )

        Rotate ->
            ( { model
                | currentPiece = rotateWherePossible model.board model.currentPiece
              }
            , Cmd.none
            )

moveIfPossible : Direction -> Board -> Piece -> Piece
moveIfPossible direction board piece =
    let
        movedPiece =
            Piece.move direction piece
    in
        if movedPiece |> Board.legalOn board then
            movedPiece
        else
            piece

{-| If the piece can be legally rotated at its current positions, or at any
space adjacent position up to two spaces away, perform rotation. Otherwise
return piece as is.
-}
rotateWherePossible : Board -> Piece -> Piece
rotateWherePossible board piece =
    let
        possiblePositions =
            [ piece |> Piece.rotate
            , piece |> Piece.move Left |> Piece.rotate
            , piece |> Piece.move Right |> Piece.rotate
            , piece |> Piece.move Left |> Piece.move Left |> Piece.rotate
            , piece |> Piece.move Right |> Piece.move Right |> Piece.rotate
            ]
    in
        possiblePositions
            |> List.filter (Board.legalOn board)
            |> List.head
            |> Maybe.withDefault piece
<file_sep>module Types.GameState exposing (GameState(..), score, addPoints)

type GameState
    = NotStarted
    | Paused Score
    | Running Score
    | GameOver Score

type alias Score =
    Int

score : GameState -> Int
score state =
    case state of
        NotStarted ->
            0

        Paused score ->
            score

        Running score ->
            score

        GameOver score ->
            score

addPoints : Int -> GameState -> GameState
addPoints n state =
    case state of
        NotStarted ->
            NotStarted

        Paused score ->
            Paused <| score + n

        Running score ->
            Running <| score + n

        GameOver score ->
            GameOver <| score + n
<file_sep>const path = require('path');
const merge = require('webpack-merge');
const common = require('./webpack.common.js');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const ExtractTextPlugin = require("extract-text-webpack-plugin");
const CleanWebpackPlugin = require('clean-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = merge(common, {
    devtool: 'inline-source-map',

    plugins: [
        new CleanWebpackPlugin([path.join(__dirname, 'build')]),

        new ExtractTextPlugin({
            disable: true,
        }),

        new HtmlWebpackPlugin({
            template: './static/index.html',
        }),
    ],

    module: {
        rules: [
            {
                test: /\.elm$/,
                exclude: [/elm-stuff/, /node_modules/],
                loader: 'elm-hot-loader!elm-webpack-loader?verbose=true&warn=true&debug=true&cwd='+__dirname,
            },
        ]
    },

    devServer: {
        inline: true,
        historyApiFallback: true,
        stats: { colors: true },
        contentBase: './src',
    },
});
<file_sep>import { Main } from './Main.elm';

var app = Main.embed(document.getElementById('app-wrapper'));
<file_sep>#!/usr/bin/env bash
set -e

npm run build

git checkout gh-pages
for file in $(ls -1 build/)
do
  cp "build/$file" .
  git add $file
  echo "updated $file"
done

if git diff-index --quiet HEAD -- ; then
  echo
  echo '! No changes to deploy.'
  echo
  git checkout master
  exit 0
fi

git commit -m "Deploy updated version to GitHub Pages"
git push -f origin gh-pages
git checkout master
<file_sep>Tetris implemented in Elm.

Try it out: https://kvalle.github.io/elm-tetris/

![Screenshot of game](screenshot.png)
<file_sep>module Config
    exposing
        ( width
        , height
        , pixelSize
        )

width : number
width =
    15

height : number
height =
    25

pixelSize : number
pixelSize =
    30
<file_sep>module Types.Common exposing (Direction(..), Color(..))

type Direction
    = Down
    | Left
    | Right

type Color
    = Blue
    | Yellow
    | Red
    | Green
    | Purple
    | Orange
    | Gray
<file_sep>module Types.Piece exposing (Piece, empty, isEmpty, positions, random, move, rotate)

import Random exposing (Generator)
import List.Nonempty exposing (Nonempty(..))
import Types.Common exposing (Color(..), Direction(..))
import Types.Pos as Pos exposing (Pos)
import Config

type alias Piece =
    { -- cell type for this piece
      color : Color
    , -- center position of piece
      pos : Pos
    , -- relative coordinates of blocks within piece
      blocks : List ( Int, Int )
    }

empty : Piece
empty =
    { color = Blue, pos = Pos 0 0, blocks = [] }

isEmpty : Piece -> Bool
isEmpty piece =
    piece.blocks == []

positions : Piece -> List Pos
positions piece =
    piece.blocks
        |> List.map (Tuple.mapFirst <| (+) piece.pos.row)
        |> List.map (Tuple.mapSecond <| (+) piece.pos.col)
        |> List.map (uncurry Pos)

pieces : Nonempty Piece
pieces =
    let
        theI =
            { color = Red
            , pos = { row = 1, col = Config.width // 2 }
            , blocks = [ ( -1, 0 ), ( 0, 0 ), ( 1, 0 ), ( 2, 0 ) ]
            }

        theL =
            { color = Yellow
            , pos = { row = 1, col = Config.width // 2 }
            , blocks = [ ( -1, 0 ), ( 0, 0 ), ( 1, 0 ), ( 1, 1 ) ]
            }

        theJ =
            { color = Purple
            , pos = { row = 1, col = Config.width // 2 }
            , blocks = [ ( -1, 0 ), ( 0, 0 ), ( 1, 0 ), ( 1, -1 ) ]
            }

        theT =
            { color = Green
            , pos = { row = 1, col = Config.width // 2 }
            , blocks = [ ( -1, 0 ), ( 0, 0 ), ( 0, 1 ), ( 1, 0 ) ]
            }

        theO =
            { color = Blue
            , pos = { row = 1, col = Config.width // 2 }
            , blocks = [ ( -1, 0 ), ( -1, 1 ), ( 0, 0 ), ( 0, 1 ) ]
            }

        theS =
            { color = Orange
            , pos = { row = 1, col = Config.width // 2 }
            , blocks = [ ( -1, 0 ), ( -1, 1 ), ( 0, -1 ), ( 0, 0 ) ]
            }

        theZ =
            { color = Gray
            , pos = { row = 1, col = Config.width // 2 }
            , blocks = [ ( -1, -1 ), ( -1, 0 ), ( 0, 0 ), ( 0, 1 ) ]
            }
    in
        Nonempty theI
            [ theL, theJ, theT, theO, theS, theZ ]

random : Generator Piece
random =
    List.Nonempty.sample pieces

move : Direction -> Piece -> Piece
move direction piece =
    let
        fn =
            case direction of
                Down ->
                    Pos.mapRow <| (+) 1

                Left ->
                    Pos.mapCol <| flip (-) 1

                Right ->
                    Pos.mapCol <| (+) 1
    in
        { piece | pos = fn piece.pos }

rotate : Piece -> Piece
rotate piece =
    { piece
        | blocks = piece.blocks |> List.map (\( row, col ) -> ( -col, row ))
    }
<file_sep>module Model exposing (..)

import Messages exposing (Msg(..))
import Types.Board as Board exposing (Board)
import Types.Piece as Piece exposing (Piece)
import Types.GameState exposing (GameState(..))

type alias Model =
    { board : Board
    , currentPiece : Piece
    , nextPiece : Piece
    , state : GameState
    , speed : Int
    }

init : ( Model, Cmd Msg )
init =
    ( { board = Board.empty
      , currentPiece = Piece.empty
      , nextPiece = Piece.empty
      , state = NotStarted
      , speed = 1
      }
    , Cmd.none
    )
<file_sep>module View exposing (view)

import Collage exposing (defaultLine)
import Color
import Config
import Element
import Html exposing (..)
import Html.Attributes exposing (..)
import Model exposing (Model)
import Types.Board as Board exposing (Board, Cell(..))
import Types.Common exposing (Color(..), Direction(..))
import Types.GameState as GameState exposing (GameState(..))
import Types.Piece as Piece exposing (Piece)
import Types.Pos as Pos exposing (Pos)

view : Model -> Html msg
view model =
    div [ class "game" ]
        [ div [ class "board" ]
            [ tetrisCanvas model
            , overlay model.state
            ]
        , div [ class "info" ]
            [ div [ class "title" ]
                [ text "Tetris" ]
            , div [ class "info-item status" ]
                [ text <| "score: " ++ toString (GameState.score model.state) ]
            , div [ class "info-item status" ]
                [ text <| "speed: " ++ toString model.speed ]
            , div [ class "info-item status" ]
                [ if not <| Piece.isEmpty model.nextPiece then
                    text "next piece: "
                  else
                    text ""
                ]
            , div [ class "info-item status" ]
                [ nextPieceCanvas model.nextPiece ]
            , div [ class "info-item controls" ]
                [ text "move: ⬅/➡/⬇"
                , br [] []
                , text "rotate: ⬆"
                , br [] []
                , text "drop: ENTER"
                , br [] []
                , text "pause: P"
                ]
            ]
        ]

overlay : GameState -> Html msg
overlay state =
    case state of
        NotStarted ->
            div [ class "board-overlay" ]
                [ text "press SPACE to begin" ]

        Paused _ ->
            div [ class "board-overlay" ]
                [ h1 [] [ text "PAUSED" ]
                , text "press R to resume"
                , br [] []
                , br [] []
                , text "press N for new game"
                ]

        GameOver _ ->
            div [ class "board-overlay board-overlay--transparent" ]
                [ h1 [] [ text "GAME OVER" ]
                , text "press SPACE for new game"
                ]

        Running _ ->
            text ""

tetrisCanvas : Model -> Html msg
tetrisCanvas model =
    model
        |> renderBoard
        |> Collage.collage
            (Config.width * Config.pixelSize - Config.pixelSize // 2)
            (Config.height * Config.pixelSize - Config.pixelSize // 2)
        |> Element.toHtml

nextPieceCanvas : Piece -> Html msg
nextPieceCanvas piece =
    let
        renderBlock ( rowOffset, colOffset ) =
            Collage.square Config.pixelSize
                |> Collage.filled (cellColor <| Filled piece.color)
                |> Collage.move
                    ( toFloat colOffset * Config.pixelSize
                    , toFloat rowOffset * Config.pixelSize * -1
                    )
    in
        piece.blocks
            |> List.map renderBlock
            |> Collage.collage
                (Config.pixelSize * 4)
                (Config.pixelSize * 4)
            |> Element.toHtml

renderBoard : Model -> List Collage.Form
renderBoard model =
    let
        board =
            model.board
                |> Board.toPosList
                |> List.map (uncurry renderCell)

        piece =
            model.currentPiece
                |> Piece.positions
                |> List.map (\pos -> ( pos, Filled model.currentPiece.color ))
                |> List.map (uncurry renderCell)

        shadow =
            if Piece.isEmpty model.currentPiece then
                []
            else
                model.currentPiece
                    |> Board.moveToBottom model.board
                    |> Piece.positions
                    |> List.map (\pos -> ( pos, Filled model.currentPiece.color ))
                    |> List.map (uncurry renderCell)
                    |> List.map (Collage.alpha 0.1)
    in
        board ++ shadow ++ piece

renderCell : Pos -> Cell -> Collage.Form
renderCell pos cell =
    Collage.square Config.pixelSize
        |> Collage.filled (cellColor cell)
        |> Collage.move (toCanvasCoord pos)

cellColor : Cell -> Color.Color
cellColor cell =
    case cell of
        Empty ->
            Color.white

        Filled Blue ->
            Color.blue

        Filled Red ->
            Color.red

        Filled Green ->
            Color.green

        Filled Yellow ->
            Color.yellow

        Filled Purple ->
            Color.purple

        Filled Gray ->
            Color.darkGray

        Filled Orange ->
            Color.orange

toCanvasCoord : Pos -> ( Float, Float )
toCanvasCoord pos =
    ( toFloat <| (pos.col - (Config.width // 2)) * Config.pixelSize
    , toFloat <| (Config.height - 1 - (pos.row + (Config.height // 2))) * Config.pixelSize
    )

branch_name: refs/heads/master

languages: Markdown Elm JavaScript Shell

repo_language: Markdown

repo_name: kvalle/elm-tetris


text:
<repo_name>taraskaduk/duolingo<file_sep>/README.md
# Duolingo user scripts and bookmarklets

**Duolingo Weekly Progress**

* Shows you a progress chart for the last 7 days.
* Works on your home page.
* Works on all profiles (but only shows the language the person is currently learning).
* [See details/screenshots](http://www.code-poet.net/duolingo/weekly-progress.html) or [install userscript](https://github.com/vaughanchandler/duolingo/raw/master/duolingo-weekly-progress.user.js).

**Duolingo Review**

* Shows you all the questions and answers from a lesson or practice after you finish it.
* [See details/screenshots](http://www.code-poet.net/duolingo/review.html) or [install userscript](https://github.com/vaughanchandler/duolingo/raw/master/duolingo-review.user.js)

**Duolingo Incubator Stats**

* Shows you the completion for phase 1 languages as percentages, rounded to 1 decimal place.
* [See details/screenshots](http://www.code-poet.net/duolingo/incubator-stats.html), [install userscript](https://github.com/vaughanchandler/duolingo/raw/master/duolingo-incubator-stats.user.js) or [install bookmarklet](http://www.code-poet.net/duolingo/incubator-stats.html)

## User scripts

### Installing

1. If haven't already, install the appropriate extension for your browser (restarting your browser afterwards if necessary):
 * Chrome: [Tampermonkey](https://chrome.google.com/webstore/detail/tampermonkey/dhdgffkkebhmkfjojejmpbldmpobfkfo?hl=en)
 * Chromium: [Tampermonkey](https://chrome.google.com/webstore/detail/tampermonkey/dhdgffkkebhmkfjojejmpbldmpobfkfo?hl=en)
 * Firefox: [Greasemonkey](https://addons.mozilla.org/en-US/firefox/addon/greasemonkey/)
 * Safari: [JavaScript Blocker](http://javascript-blocker.toggleable.com/)
1. Click on the user script installation link under the user script's description above.
1. Confirm the installation when prompted.

### Uninstalling

1. Follow the uninstall steps for the browser/extension you're using:
 * Chrome: [Tampermonkey](http://tampermonkey.net/faq.php?ext=dhdg#Q101)
 * Chromium: [Tampermonkey](http://tampermonkey.net/faq.php?ext=dhdg#Q101)
 * Firefox: [Greasemonkey](http://wiki.greasespot.net/Greasemonkey_Manual:Script_Management)
 * Safari: [JavaScript Blocker](http://javascript-blocker.toggleable.com/)

## Bookmarklets

### Installing

1. Click on the installation link under the user script's description above.
1. Follow the bookmarklet instructions on that page.

### Uninstalling

1. Delete the bookmarklet as you would delete any other bookmark.

## Beta versions

### Duolingo Stats

Duolingo Stats is intended to be a replacement for Duolingo Weekly Progress. You should uninstall or disable Duolingo Weekly Progress if you install this.

Current features:

* Shows you a progress chart for the last 7 days, on your home page and on other people's profiles.
* Shows you other people's trees on their profile (after you click on "Show the tree").

Planned features:

* Show all certificates a person has earned, including the score for each certificate and the date/time test was taken.
* Show the amount of points a person has in each language.
* Show a person's all-time ranking among their followers.

Known bugs / limitations:

* Progress charts and trees are only shown for the language the person is currently learning.
* Trees don't show divisions between sections or bonus skills.
* The text for showing/hiding the tree is still only in English.
* The progress chart on your home page won't update after using immersion until you refresh the page or do a lesson/practice.
* Still being tested.

[Install Duolingo Stats](https://github.com/vaughanchandler/duolingo/raw/master/duolingo-stats.user.js) (instructions above)

repo_name: taraskaduk/duolingo


text:
<repo_name>muchmala/muchmala-common<file_sep>/lib/storage/s3.js
var fs = require('fs'),
    path = require('path'),
    url = require('url'),
    knox = require('knox'),
    async = require('async'),
    xml2js = require("xml2js"),
    misc = require('../misc');

exports.createStorage = createStorage;

var TEMPORARY_STORAGE = '/tmp';

function createStorage(options, callback) {
    process.nextTick(function() {
        callback(null, new S3Storage(knox.createClient(options)));
    });
}

function S3Storage(knoxClient) {
    this._knoxClient = knoxClient;
}

S3Storage.prototype.put = function(src, dst, callback) {
    this._knoxClient.putFile(src, dst, function(err, res) {
        if (err) {
            return callback(err);
        }

        if (res.statusCode != 200) {
            var message = 'PUT Failed!\n';
            message += 'HTTP ' + res.statusCode + '\n';
            message += JSON.stringify(res.headers);
            return callback(new Error(message));
        }

        callback(null);
    });
};

S3Storage.prototype.get = function(filePath, callback) {
    var self = this;
    var dirName = generateUniqueDirName();
    var localFilePath = dirName + '/' + path.basename(filePath);
    var file;

    async.waterfall([function(callback) {
        fs.mkdir(dirName, 0777, callback);

    }, function(callback) {
        file = fs.createWriteStream(localFilePath).on('open', function(fd) {
            callback();
        });

    }, function(callback) {
        self._knoxClient.getFile(filePath, function(err, res){
            if (err) {
                callback(err);
            }

            res.setEncoding('binary');

            res.on('data', function(data) {
                file.write(data, 'binary');
            });

            res.on('end', callback);
        });

    }], function(err) {
        if (file) {
            file.end();
        }

        if (err) {
            return callback(err);
        }

        callback(null, localFilePath);
    });
};

S3Storage.prototype.exists = function(filePath, callback) {
    this._knoxClient.getFile(filePath, function(err, res){
        if (err) {
            callback(err);
        }

        callback(null, res.statusCode == 200);
    });
};

S3Storage.prototype.listDir = function(filePath, callback) {
    filePath = path.normalize('/' + filePath + '/').substr(1);
    this._knoxClient.get(url.format({
        pathname: '/',
        query: {
            delimiter: '/',
            prefix: filePath
        }
    })).on('response', function(res){
        if (res.statusCode != 200) {
            var message = 'LIST Failed!\n';
            message += 'HTTP ' + res.statusCode + '\n';
            message += JSON.stringify(res.headers);
            return callback(new Error(message));
        }

        res.setEncoding('utf8');

        var parser = new xml2js.Parser();
        parser.addListener('end', function(result) {
            var files = (result.Contents) ? Array.prototype.concat(result.Contents) : [];
            var dirs =  (result.CommonPrefixes) ? Array.prototype.concat(result.CommonPrefixes) : [];
            var prefixLength = filePath.length;

            var contents = {
                files: {},
                dirs: {}
            };

            files.forEach(function(file) {
                contents.files[file.Key.slice(prefixLength)] = {
                    path: file.Key,
                    change: new Date(file.LastModified),
                    size: +file.Size
                };
            });
            dirs.forEach(function(dir) {
                contents.dirs[dir.Prefix.slice(prefixLength, -1)] = {
                    path: dir.Prefix
                };
            });

            callback(null, contents);
        });

        var response = '';
        res.on('data', function(chunk){
            response += chunk;
        });

        res.on('end', function() {
            parser.parseString(response);
        });
    }).end();
};

function generateUniqueDirName() {
    return TEMPORARY_STORAGE + '/get-' + misc.getUniqueString();
}
<file_sep>/README.md
Muchmala-common
===============

This package contains all common stuff of Muchamla:
* database models
* puzzle generator
* puzzle storage
* logger
* some misc functions

## Documentation

### muchamlaCommon.db (database models)

Contains all Muchmala models and some helper methods.

#### connect(options, callback)

Establishes connection to mongoDB.

    options {
        user        (required)
        host        (required)
        database    (required)
    }

    callback(err)   function triggered when connection is established

Example

    var db = require('muchmala-common').db;

    db.connect({
        user:     "mongodb",
        host:     "127.0.0.1",
        database: "muchmala"
    }, function(err) {
        if (err) {
            console.error(err);
            return;
        }

        console.log("Connection is established");
    });

#### generateId()

Generates new ObjectId and returns it's string representation.

Example

    var db = require('muchmala-common').db;

    var newId = db.generateId();

#### Sessions

User sessions model

#### Puzzles

Puzzles model

#### Users

Users model

### muchamlaCommon.puzzleGenerator (puzzle generator)

Creates puzzle map and covers.

#### createPuzzle(imagePath, options, callback)

Generates puzzle map and sprites for puzzle from image imagePath

    imagePath       path to image
    options {
        name        (string,  optional) Name of the resulting puzzle. If this option is omitted, file name is taken.
        pieceSize   (integer, optional) Size of one tile in pixels. Default value is 120.
        private     (boolean, optional) If true, puzzle will not be present in general queue.
    }
    callback(err, metadata)   function triggered when all images are generated
        metadata {
            name         Puzzle name
            pieceSize    Size of one tile's size in pixels
            spriteSize   Size of sprite in pixels
            invisible    Flag, which shows if puzzle should pe present in general queue
            resultDir    Directory, where you can find all generated stuff
            hLength      ?
            vLength      ?
            piecesMap    Map which contains information about location of the pieces on the puzzle
        }

Example

    var puzzleGenerator = require('muchmala-common').puzzleGenerator;

    puzzleGenerator.createPuzzle('./img.png', {}, function(err, metadata) {
        if (err) {
            console.error(err);
            return;
        }

        console.log("Puzzle is created: " + metadata);
    });

#### createCovers(size, callback)

Creates three covers for puzzle of given size.

    size            integer, size of the side of tile in pixels
    callback(err, metadata)   function, triggered when covers are created
        metadata {
            size         Size of one tile's size in pixels
            resultDir    Directory, where you can find all generated stuff
        }

Example

    var puzzleGenerator = require('muchmala-common').puzzleGenerator;

    puzzleGenerator.createCovers(250, function(err, metadata) {
        if (err) {
            console.error(err);
            return;
        }

        console.log("Covers are created: " + metadata);
    });

#### validators.append(newValidator)

Appends new validator to validators list.
All the validators are executed after loading image. If one fails, image processing is stopped.

    newValidator(image, callback)    function. Accepts image(canvas) object as argument.
                                     Triggers callback with error if validation fails.

Example

    var puzzleGenerator = require('muchmala-common').puzzleGenerator;

    puzzleGenerator.validators.append(function(image, callback) {
        if (image.width != image.height) {
            return callback("Image is not of square form");
        }

        callback();
    });

#### validators.getWidthValidator(minWidth, maxWidth)

Returns validator to accept images only of given width.

    minWidth        integer
    maxWidth        integer

Example

    var puzzleGenerator = require('muchmala-common').puzzleGenerator;

    puzzleGenerator.validators.append(
        puzzleGenerator.validators.getWidthValidator(800, 1024);
    );

#### validators.getHeightValidator(minHeight, maxHeight)

Returns validator to accept images only of given height.

    minHeight       integer
    maxHeight       integer

Example

    var puzzleGenerator = require('muchmala-common').puzzleGenerator;

    puzzleGenerator.validators.append(
        puzzleGenerator.validators.getHeightValidator(800, 1024);
    );

### muchamlaCommon.storage (puzzle storage)

Abstraction layer over different types of storage (like file storage, amazon s3, etc)

#### createStorage(type, options, callback)

Factory. Creates storage of given type

    type       (string) [file|s3]
    options    (object) options for given storage
    callback(err, storage)    callback, triggered when storage is ready
        storage               instance of storage

        storage.put(src, dst, callback)  copies file into storage
            src              (string) path to file
            dst              (string) path to file in storage
            callback(err)    function, triggered when transaction is done

        storage.get(path, callback)      copies file from storage
            path             (string) path to file in storage
            callback(err, localFilePath)  function, triggered when transaction is done
                localFilePath   location of the file in local file system

        storage.exists(path, callback)   checks if file exists in storage
            path             (string) path to file in storage
            callback(err, exists)  function, triggered when check is done
                exists   boolean flag. If true, then file exists

        storage.listDir(path, callback)  lists directory
            path             (string) path to file in storage
            callback(err, contents)  function, triggered when check is done
                contents     object with files and folders under path in following format:
                            { files:
                               { 'qwe.jpg':
                                  { path: 'qwe.jpg',
                                    change: Wed, 01 Jun 2011 15:18:57 GMT,
                                    size: 279092 } },
                              dirs:
                               { asd: { path: 'asd/' },
                                 covers: { path: 'covers/' },
                                 puzzles: { path: 'puzzles/' } } }

Example

    var storage = require('muchmala-common').storage;

    storage.createStorage('s3', {
        key: '<KEY>',
        secret: '<KEY>dfn',
        bucket: 'static.dev.muchmala.com'
    }, function(err, storage) {
        if (err) {
            console.error(err);
            return;
        }

        storage.exists('/some/path/some-file.qwe', function(err, exists) {
            if (exists) {
                console.log('file exists');
            } else {
                console.log('file does not exists');
            }
        });
    });

### muchamlaCommon.logger

Logger with option of setting log level.

#### setLevel(level)

Sets logging level

    level        (function|integer|string)
                 0 == 'DEBUG'   == logger.debug
                 1 == 'INFO'    == logger.info
                 2 == 'WARNING' == logger.warning
                 3 == 'ERROR'   == logger.error

Example

    var logger = require('muchmala-common').logger;

    logger.setLevel(logger.info);

    logger.debug('debug'); //not printed
    logger.info('info'); //is printed
    logger.warning('warning'); //is printed
    logger.error('error'); //is printed

#### debug(var[,var[, ...]])
#### info(var[,var[, ...]])
#### warning(var[,var[, ...]])
#### error(var[,var[, ...]])

### muchamlaCommon.misc (some misc functions)

#### deepExtend(object1, object2)

Extends object1 with object2

Example

    var a = {
        1: {
            x: 1,
            y: 2
        },
        2: 'xy'
    };

    require('muchmala-common').misc.deepExtend(a, {
        1: {
            y: 100
        }
    });

    console.log(a);

    //var a = {
    //    1: {
    //        x: 1,
    //        y: 100
    //    },
    //    2: 'xy'
    //};

#### getUniqueString()

Returns unique string<file_sep>/lib/generator/index.js
var path = require('path'),
    Image = require('canvas').Image,
    _ = require('underscore'),
    async = require('async'),
    cutter = require('./cutter'),
    layout = require('./layout'),
    logger = require('../logger'),
    misc = require('../misc');

exports.createPuzzle = createPuzzle;
exports.createCovers = createCovers;
exports.createFrame = createFrame;
exports.validators = {
    append: addValidators,
    getWidthValidator: getWidthValidator,
    getHeightValidator: getHeightValidator
};

var DEFAULT_PIECE_SIZE = 120;
var SPRITE_SIZE = 5;
var OUTPUT_DIR = '/tmp';

var validators = [];

function addValidators(newValidators) {
    Array.prototype.push.apply(validators, Array.prototype.concat(newValidators));
}

function getWidthValidator(minWidth, maxWidth) {
    return function(image, callback) {
        var result = null;

        if (image.width < minWidth) {
            result = {
                short: 'imageWidthSmall',
                message: 'Image has width less then ' + minWidth
            };
        }
        if (image.width > maxWidth) {
            result = {
                short: 'imageWidthBig',
                message: 'Image has width grater then ' + maxWidth
            };
        }
        callback(result);
    }
}

function getHeightValidator(minHeight, maxHeight) {
    return function(image, callback) {
        var result = null;

        if (image.height < minHeight) {
            result = {
                short: 'imageHeightSmall',
                message: 'Image has height less then ' + minHeight
            };
        }
        if (image.height > maxHeight) {
            result = {
                short: 'imageHeightBig',
                message: 'Image has height grater then ' + maxHeight
            };
        }
        callback(result);
    }
}

function createPuzzle(imagePath, options, callback) {
    if (_.isFunction(options)) {
        callback = options;
        options = {};
    }

    async.waterfall([
        function(callback) {
            loadImage(imagePath, callback);
        },
        function(image, callback) {
            validateImage(image, callback);
        },
        function(image, callback) {
            generatePieces(image, options, callback);
        }
    ], callback);
}

function createCovers(size, callback) {
    var resultDir = generateUniqueDirName('covers');

    cutter.createCovers(size, resultDir, function() {
        callback(null, {size: size, resultDir: resultDir});
    });
}

function createFrame(size, callback) {
    var resultDir = generateUniqueDirName('frame');

    cutter.createFrame(size, resultDir, function() {
        callback(null, {size: size, resultDir: resultDir});
    });
}

function generatePieces(image, options, callback) {
    var metadata = {
        name: options.name || path.basename(image.src, path.extname(image.src)),
        pieceSize: options.pieceSize || DEFAULT_PIECE_SIZE,
        resultDir: generateUniqueDirName('puzzle'),
        invisible: !!options.private,
        spriteSize: SPRITE_SIZE
    };

    logger.info('Creating puzzle:', metadata);
    logger.debug(image.width, image.height);

    var puzzle = layout.createPuzzle(image.width, image.height, metadata.pieceSize);

    logger.info('Puzzle map created.');

    _.extend(metadata, {
        hLength: puzzle.hLength,
        vLength: puzzle.vLength,
        piecesMap: puzzle.pieces
    });

    cutter.createPieces(image, metadata, function() {
        logger.info('Sprites cut and saved.');
        callback(null, metadata);
    });
}

function loadImage(imagePath, callback) {
    var image = new Image();

    image.onerror = function(err) {
        callback(err);
    };

    image.onload = function() {
        callback(null, image);
    };

    image.src = imagePath;
}

function validateImage(image, callback) {
    async.reduce(validators, [],
        function(memo, validator, callback) {
            validator(image, function(error) {
                if (error) {
                    memo.push(error);
                }
                callback(null, memo);
            });
        },
        function(err, validationErrors){
            if (validationErrors.length) {
                callback({message:'validation errors', data: validationErrors});
                return;
            }
            callback(null, image);
        });
}

function generateUniqueDirName(prefix) {
    return OUTPUT_DIR + '/' + prefix + '-' + misc.getUniqueString();
}
<file_sep>/lib/cmd.js
var _ = require('underscore'),
    spawn = require('child_process').spawn;

var subprocesses = [];
process.on('SIGINT', cleanupBeforeExit);
process.on('SIGTERM', cleanupBeforeExit);

function cleanupBeforeExit() {
    subprocesses.forEach(function(subprocess) {
        console.log('Killing subprocess', subprocess.pid);
        subprocess.kill();
    });
    console.log('All subprocesses killed, exiting');
    process.exit(0);
}

function unsudo(args, options, callback) {
    if (process.env.SUDO_USER) {
        args = ['sudo', '-u', process.env.SUDO_USER].concat(args);
    }
    var command = args.shift();
    passthru(command, args, options, callback);
}
exports.unsudo = unsudo;

function passthru(command, args, options, callback) {
    if (_.isFunction(options)) {
        callback = options;
        options = {};
    }

    if (!_.isFunction(callback)) {
        callback = null;
    }

    if (_.isEmpty(options.customFds)) {
        // FIXME: find out why next line breaks things
        //options.customFds = [process.stdin, process.stdout, process.stderr];
    }

    options.env = process.env;

    var subprocess = spawn(command, args, options);
    subprocesses.push(subprocess);
    if (callback) {
        subprocess.on('exit', function() {
            subprocesses = _.without(subprocesses, subprocess);
            callback.apply(this, Array.prototype.slice.apply(arguments));
        });
    };

    if (subprocess.stdout) {
        subprocess.stdout.on('data', function (data) {
            process.stdout.write(data);
        });
    }

    if (subprocess.stderr) {
        subprocess.stderr.on('data', function (data) {
            process.stderr.write(data);
        });
    }
}
exports.passthru = passthru;
<file_sep>/lib/queue.js
var rq = require('rq');

exports.Adapter = Adapter;

function Adapter(options) {
    var rqOptions = {
        REDIS_HOST: options.host,
        REDIS_PORT: options.port,
        REDIS_PASSWORD: <PASSWORD>,
        REDIS_DATABASE: options.database
    };

    this.listener = rq.getListener(rqOptions);
    this.publisher = rq.getPublisher(rqOptions);
}

Adapter.prototype.subscribe = function(channelName, callback) {
    this.listener.subscribe(channelName, callback);
};

Adapter.prototype.publish = function(channelName, message) {
    this.publisher.publish(channelName, message);
};

Adapter.prototype.broadcast = function(channelName, message) {
    this.publisher.broadcast(channelName, message);
};<file_sep>/lib/storage/index.js
exports.createStorage = createStorage;

var storages = {
    s3: require('./s3').createStorage,
    file: require('./file').createStorage
};

function createStorage(type, options, callback) {
    if (!(type in storages)) {
        process.nextTick(function(){
            callback(new Error("Unsupported storage: " + type));
        });
        return;
    }

    storages[type](options, callback);
}
<file_sep>/lib/storage/file.js
var fs = require('fs'),
    path = require('path'),
    util = require('util'),
    knox = require('knox'),
    async = require('async');

exports.createStorage = createStorage;

var TEMPORARY_STORAGE = '/tmp';

function createStorage(options, callback) {
    process.nextTick(function() {
        callback(null, new FileStorage(options.location));
    });
}

function FileStorage(location) {
    this._location = path.resolve(location);
}

FileStorage.prototype.put = function(src, dst, callback) {
    var srcPath = src;
    var dstPath = this._resolvePath(dst);

    createBaseDir(dstPath, 0755, function() {
        var writeStream, readStream;

        async.waterfall([function(callback) {
            writeStream = fs.createWriteStream(dstPath).on('open', function() {
                callback();
            });
        }, function(callback) {
            readStream = fs.createReadStream(srcPath).on('open', function() {
                callback();
            });
        }], function() {
            util.pump(readStream, writeStream, callback);
        });
    });
};

FileStorage.prototype.get = function(filePath, callback) {
    var self = this;

    this.exists(filePath, function(err, exists) {
        if (!exists) {
            return callback(new Error('File ' + filePath + ' does not exist in file storage.'));
        }

        callback(null, self._resolvePath(filePath));
    });
};

FileStorage.prototype.exists = function(filePath, callback) {
    var realPath = this._resolvePath(filePath);

    path.exists(realPath, function(exists) {
        if (!exists) {
            return callback(null, exists);
        }

        fs.stat(realPath, function(err, stats) {
            if (err) {
                return callback(err);
            }

            callback(null, stats.isFile());
        });
    });
};

FileStorage.prototype.listDir = function(filePath, callback) {
    filePath = path.normalize('/' + filePath + '/');
    var realPath = this._resolvePath(filePath);

    fs.readdir(realPath, function(err, files) {
        if (err) {
            files = [];
        }

        var contents = {
            files: {},
            dirs: {}
        };

        files.forEach(function(obj) {
            var stats = fs.statSync(path.resolve(realPath, obj));
            if (stats.isDirectory()) {
                contents.dirs[obj] = {
                    path: path.resolve(filePath, obj)
                };
            } else {
                contents.files[obj] = {
                    path: path.resolve(filePath, obj),
                    change: new Date(stats.mtime),
                    size: stats.size
                };
            }
        });

        callback(null, contents);
    });
};

FileStorage.prototype._resolvePath = function(filePath) {
    filePath = path.normalize('/' + filePath).substr(1);
    return path.resolve(this._location, filePath);
};

function createBaseDir(filePath, mode, callback) {
    var baseDir = path.dirname(filePath);
    path.exists(baseDir, function(exists) {
        if (exists) {
            return callback();
        }

        createBaseDir(baseDir, mode, function(err) {
            fs.mkdir(baseDir, mode, callback);
        })
    });
}

languages: Markdown JavaScript

repo_name: muchmala/muchmala-common


text:
<repo_name>ste00martin/react-express<file_sep>/client/src/App.js
import React, { Component } from 'react';
import './App.css';

function consLog(input) {
  console.log(JSON.stringify(input));
}

class App extends Component {
  state = {shortcuts: [], keyboardInput: 'cancer', translations: {}, newKey: '', newValue: ''}

  constructor(props) {
    super(props);
    this.handleChange = this.handleChange.bind(this);
  }

  getShortcuts(word) {
    return fetch('shortcuts/', {
      method: 'POST',
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        word: word
      })
    }).then(res => res.json()).then(response => {
      return {input: word, suggestions: response};
    });
  }

  setShortcut(key, value) {
    return fetch('shortcuts/new', {
      method: 'POST',
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        key: key,
        value: value
      })
    });

  }

  componentDidMount() {
    this.updateShortcuts();
  }

  updateShortcuts() {
    var words = [];
    var keyboardInput = this.state.keyboardInput;
    var translations = this.state.translations;

    words = words.concat(keyboardInput.split(' '));

    var promises = [];

    translations = Object.keys(translations).filter(obj => {
      console.log(obj);
      words.includes(obj);
    });

    words.forEach(word => {
      if (!(word in translations )) {
        promises.push(this.getShortcuts(word));
      }
    });

    Promise.all(promises).then(responses => {
      responses.forEach(response => {
        if(response.suggestions.length > 0) {
          translations[response.input] = response.suggestions;

        } else {
          // word isn't in the translations,
          // nor are there shortcuts. delete translation
          delete translations[response.input];
        }
      });

    }).then(() =>{
      this.setState({
        translations: translations
      });
    });
  }

  handleNewShortcuts = () => {
    var key = this.state.newKey;
    var value = this.state.newValue;
    consLog(value);

    var output = this.setShortcut(key, value);
    var updatedTranslations = this.state.translations;
    delete updatedTranslations[key];
    this.setState({key: '', value: '', translations: updatedTranslations}, () => {
      this.updateShortcuts();
    });
  }

  handleChange(event) {
    this.setState({[event.target.name]: event.target.value} , () => {
      this.updateShortcuts();
    });
  }

  render() {
    var rows = [];
    var index = 0;

    Object.keys(this.state.translations).forEach(key => {

      var innerTranslations = [];

      this.state.translations[key].forEach((potential) => {
        index++;
        innerTranslations.push({potential.text}	);
      });
      index++;

      rows.push(
{key}	{innerTranslations}
);
    });

    return (

Diagnosis

          <input type="text" name="keyboardInput" value={this.state.keyboardInput} onChange={this.handleChange} />

                Input Text
                Potential Terms

              {rows}

          Add new shortcut:
          <input type="text" name="newKey" value={this.state.newKey}
            onChange={this.handleChange}/>
          <input type="text" name="newValue" value={this.state.newValue}
            onChange={this.handleChange}/>

          <button onClick={this.handleNewShortcuts}>
            Add New Shortcut
          </button>

    );
  }
}

export default App;
<file_sep>/routes/shortcuts.js
var express = require('express');
var router = express.Router();

const autocomplete = require('../autocomplete.js');
var Shortcuts = new autocomplete();

console.log("start");
console.log(Shortcuts.get("cancer"));

router.post('/', function(req, res) {

  res.contentType('application/json');

  var diagnosis = req.body.word;
  console.log("diagnosis: "+ diagnosis + "wordcount:" + diagnosis.length);
  var response = Shortcuts.get(diagnosis);
  console.log("response: " + JSON.stringify(response));

  res.json(response);
});

router.post('/new', function(req, res) {

  res.contentType('application/json');

  var key = req.body.key;
  var value = req.body.value;

  Shortcuts.set(key, value);
  console.log(key);

  var response = Shortcuts.get(key);

  console.log(value);
  console.log("response: "+ JSON.stringify(response));
  res.json(response);
});

module.exports = router;
<file_sep>/autocomplete.js
'use strict';

// The getter and setter for the autosugesstions

var fs = require("fs");

class Suggestions {
  constructor() {
    var diagnosisFile = fs.readFileSync("./short-diagnoses.txt", "utf-8");
    var textByLine = diagnosisFile.split("\n");

    this.output = {};

    textByLine.forEach(diagnosis => {

      var multiline = diagnosis.split(' ');
      if (multiline.length > 1) {
        multiline.forEach(word => {

          this.set(word, diagnosis);

        });
      }

    });
  }

  get(key) {
    var result = this.output[key];
    if (result == null) {
      result = [];
    }
    return result;
  }

  set(key, val) {
    var existing = this.get(key);
    var newVal = [{text: val}];
    this.output[key] = newVal.concat(existing);
  }
}

module.exports = Suggestions;

repo_language: JavaScript


text:
<repo_name>MarioBatalha/getShoppingCart<file_sep>/README.md
# getShoppingCart
Codenation

repo_name: MarioBatalha/getShoppingCart


text:
<repo_name>mpresident14/HerokuTestApp<file_sep>/Procfile
web: java $JAVA_OPTS -Dserver.port=$PORT -jar target/HerokuTestApp-1.0.jar<file_sep>/README.md
# HerokuTestApp
Testing out Heroku

languages: Markdown Procfile


text:
<file_sep>using ORPortal_MVC.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace ORPortal_MVC.Controllers
{
    public class HomeController : Controller
    {
        //
        // GET: /Home/

        public ActionResult Index()
        {
            using (ORPortal_Db db = new ORPortal_Db())
            {
                var model = from r in db.MachineGroups
                            select r;
                int total = model.Count();
                ViewBag.total = total;
                foreach (var item in model)
                {
                    return View(item);
                }
                return View();
            }
        }
        [HttpGet]
        public ActionResult Menu()
        {
            MachineGroup group = new MachineGroup();
            return View(group);
        }
        [HttpPost]
        public ActionResult Menu(MachineGroup group )
        {
            ViewBag.Name = group.Name;
            return View();
        }
        public ActionResult Login()
        {

            return View();
        }
        public ActionResult MachineSelection()
        {
            using (ORPortal_Db db = new ORPortal_Db())
            {

                var machine = from r in db.Machines
                              select r.Name;
                int total = machine.Count();
                ViewBag.machine = total;
                List<Machine> name = new List<Machine>();
                foreach (var item in machine)
                {
                    Machine MachineList = new Machine();
                    MachineList.Name = item.ToString();

                    name.Add(MachineList);

                }
                return View(name);
                //return View();
            }

        }

        //protected override void Dispose(bool disposing)
        //{
        //    db.Dispose();
        //    base.Dispose(disposing);
        //}

    }
}
<file_sep>namespace ORPortal_MVC.Migrations
{
    using ORPortal_MVC.Models;
    using System;
    using System.Data.Entity;
    using System.Data.Entity.Migrations;
    using System.Linq;

    internal sealed class Configuration : DbMigrationsConfiguration<ORPortal_MVC.Models.ORPortal_Db>
    {
        public Configuration()
        {
            AutomaticMigrationsEnabled = true;
        }

        protected override void Seed(ORPortal_MVC.Models.ORPortal_Db context)
        {
            context.MachineGroups.AddOrUpdate(i => i.Name,

                   new MachineGroup { Name = "Che", Id=1 },
                   new MachineGroup { Name = "AirCleaner", Id=2 },
                   new MachineGroup { Name = "TubeFinal", Id=3 },
                   new MachineGroup { Name = "Group1", Id=4 }

                 );
            context.Machines.AddOrUpdate(i => i.Name,

                   new Machine { Name = "Che", Id = 1 },
                   new Machine { Name = "AirCleaner", Id = 2 },
                   new Machine { Name = "TubeFinal", Id = 3 },
                   new Machine { Name = "Group1", Id = 4 }

                 );
            context.Users.AddOrUpdate(t => t.Name,
                new User { Name = "user1", Password = "<PASSWORD>" }
                    );

        }
    }
}
<file_sep>using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;

namespace ORPortal_MVC.Models
{
    public class ORPortal_Db:DbContext
    {
        public ORPortal_Db()
            : base("name=DefaultConnection")
        {

        }
        public DbSet<Machine> Machines { get; set; }
        public DbSet<MachineGroup> MachineGroups { get; set; }
        public DbSet<User> Users { get; set; }
    }
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace ORPortal_MVC.Models
{
    public class Machine
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public double TOS { get; set; }
        public int Pulses { get; set; }
        public int Pieces { get; set; }
        public double Rmin { get; set; }
        public double Rmax { get; set; }
        public double Omin { get; set; }
        public double Omax { get; set; }
        public double Gmin { get; set; }
        public double Gmax { get; set; }
        public Nullable<int> MachineGroupId { get; set; }
        public Nullable<double> MPDuration { get; set; }
        public Nullable<double> StopCloseDuration { get; set; }
    }
}

repo_language: C#


text:
<repo_name>Hungry-and-Tired/teach-demo<file_sep>/README.md
# teach-demo
简单样例

repo_name: Hungry-and-Tired/teach-demo